PopufareAPI.py 30 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064
  1. #!/usr/bin/python3
  2. #
  3. # Copyright (c) 2019 Clementine Computing LLC.
  4. #
  5. # This file is part of PopuFare.
  6. #
  7. # PopuFare is free software: you can redistribute it and/or modify
  8. # it under the terms of the GNU Affero General Public License as published by
  9. # the Free Software Foundation, either version 3 of the License, or
  10. # (at your option) any later version.
  11. #
  12. # PopuFare is distributed in the hope that it will be useful,
  13. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. # GNU Affero General Public License for more details.
  16. #
  17. # You should have received a copy of the GNU Affero General Public License
  18. # along with PopuFare. If not, see <https://www.gnu.org/licenses/>.
  19. #
  20. ## WORK IN PROGRESS
  21. import json
  22. import mysql.connector
  23. import time
  24. import datetime
  25. import copy
  26. import hashlib
  27. #conn = mysql.connector.connect(user='bus', password='bus', host='localhost', database='busdb', port=3306)
  28. _USER = 'busapi'
  29. _PASSWORD = 'bus'
  30. _HOST = 'localhost'
  31. _DATABASE = 'busdb'
  32. _PORT = 5506
  33. Function = [
  34. "User",
  35. "Card",
  36. "Pass",
  37. "Log",
  38. "PricePoints",
  39. "AdminGetCard", "AdminGetCards", "AdminGetPass", "AdminGetUser",
  40. "AdminGetAdmin", "AdminGetPassesOnCard", "AdminGetPendingQueue", "AdminProcessPendingQueue",
  41. "AdminRemovePendingQueue", "AdminCreateCardBlock", "AdminCreateCard", "AdminSetUser",
  42. "AdminSetAdmin", "AdminAddPass", "AdminAddCard", "AdminAddUser",
  43. "AdminAddAdmin", "AdminRemovePass", "AdminRemovePasses", "AdminRemoveCard",
  44. "AdminRemoveUser", "AdminRemoveAdmin", "AdminTransferCard", "AdminTransferPass",
  45. "AdminGetPassOptions", "AdminAddCardToUser", "AdminRemoveCardFromUser", "AdminGetAdminPermissions",
  46. "AdminAddAdminPermissions", "AdminRemoveAdminPermissions", "AdminAddAdminApiPermissions", "AdminRemoveAdminApiPermissions",
  47. "AdminSetAdminApiPermissions", "AdminGetCustomCard", "AdminGetAdmins", "AdminSearchCards",
  48. "AdminSearchUsers", "AdminSearchAdmins"]
  49. PASS_FIELDS = ["logical_card_id", "issued", "activated", "deactivated", "firstused", "lastused",
  50. "nrides_orig", "nrides_remain", "nday_orig", "nday_expiration",
  51. "active", "expired", "queue_order",
  52. "rule", "comment", "paytype" ]
  53. CARD_FIELDS = ["mag_token", "rfid_token", "comment", "userid", "issued", "deactivated", "lastused",
  54. "firstused", "group_id", "issuetype"]
  55. USER_FIELDS = ["username", "comment", "first_name", "last_name", "phone",
  56. "email", "address", "city", "state", "zip", "passwordhash",
  57. "shipping_address", "shipping_city", "shipping_state", "shipping_zip",
  58. "shipping_name", "shipping_country_code", "shipping_country_name"]
  59. GROUP_FIELDS = ["id", "group_id", "group_name"]
  60. RULECLASS_FIELDS = ["id", "group_id", "group_name"]
  61. def Request(ctx):
  62. _conn = mysql.connector.connect(user=_USER, password=_PASSWORD, host=_HOST, database=_DATABASE, port=_PORT)
  63. res = {}
  64. if "function" in ctx:
  65. if ctx["function"] == "CardInfo":
  66. res = CardInfo(_conn, ctx)
  67. elif ctx["function"] == "UserInfo":
  68. res = UserInfo(_conn, ctx)
  69. elif ctx["function"] == "User":
  70. res = User(_conn, ctx)
  71. elif ctx["function"] == "Card":
  72. res = Card(_conn, ctx)
  73. elif ctx["function"] == "Pass":
  74. res = Pass(_conn, ctx)
  75. elif ctx["function"] == "Group":
  76. res = Group(_conn, ctx)
  77. elif ctx["function"] == "Ruleclass":
  78. res = Ruleclass(_conn, ctx)
  79. elif ctx["function"] == "RecycleCard":
  80. res = RecycleCard(_conn, ctx)
  81. elif ctx["function"] == "AddCardBlock":
  82. res = AddCardBlock(_conn, ctx)
  83. elif ctx["function"] == "Search":
  84. res = Search(_conn, ctx)
  85. _conn.close()
  86. return res
  87. ## _ _ __
  88. ## ___ __ _ _ __ __| (_)_ __ / _| ___
  89. ## / __/ _` | '__/ _` | | '_ \| |_ / _ \
  90. ## | (_| (_| | | | (_| | | | | | _| (_) |
  91. ## \___\__,_|_| \__,_|_|_| |_|_| \___/
  92. ##
  93. def CardInfo(db, ctx):
  94. card_res = {}
  95. action = "get"
  96. if "action" in ctx:
  97. action = ctx["action"]
  98. if action == "get":
  99. print("CardInfo:", ctx)
  100. cardid = -1
  101. if "logical_card_id" in ctx:
  102. cardid = ctx["logical_card_id"]
  103. card_res["logical_card_id"] = cardid
  104. card_res = Card(db, {"action":"get", "logical_card_id": cardid})
  105. card_res["pass"] = []
  106. if card_res["result"] == "success":
  107. ## through each of the passes on the card
  108. ##
  109. pass_query = "select user_pass_id from user_pass where logical_card_id = %s and expired = 0 order by queue_order asc"
  110. pass_cursor = db.cursor()
  111. pass_cursor.execute(pass_query, [card_res["logical_card_id"]])
  112. pass_rows = pass_cursor.fetchall()
  113. for pass_row in pass_rows:
  114. pass_res = Pass(db, {"action":"get", "user_pass_id":pass_row[0]})
  115. card_res["pass"].append(pass_res)
  116. card_res["user"] = {}
  117. if ((card_res["userid"] is not None) and (int(card_res["userid"]) >= 0)):
  118. card_res["user"] = User(db, {"action":"get", "userid": card_res["userid"] })
  119. elif action == "search":
  120. card_res["cards"] = []
  121. res_cardid = Card(db, ctx)
  122. for cid in res_cardid["logical_card_ids"]:
  123. _c = CardInfo(db, {"action":"get", "logical_card_id":cid})
  124. card_res["cards"].append(_c)
  125. card_res["result"] = "success"
  126. return card_res
  127. ## _ __
  128. ## _ _ ___ ___ _ __(_)_ __ / _| ___
  129. ## | | | / __|/ _ \ '__| | '_ \| |_ / _ \
  130. ## | |_| \__ \ __/ | | | | | | _| (_) |
  131. ## \__,_|___/\___|_| |_|_| |_|_| \___/
  132. ##
  133. def UserInfo(db, ctx):
  134. res = {}
  135. res["result"] = "fail"
  136. userid = -1
  137. if ("userid" in ctx):
  138. userid = ctx["userid"]
  139. pass_fields = PASS_FIELDS.copy()
  140. card_fields = CARD_FIELDS.copy()
  141. user_fields = USER_FIELDS.copy()
  142. res["userid"] = userid
  143. cursor = db.cursor()
  144. ## fill in user data
  145. ##
  146. res["user"] = {}
  147. fields = USER_FIELDS.copy()
  148. query = "select " + ",".join(fields) + " from users where userid = %s"
  149. cursor.execute(query, [userid])
  150. row = cursor.fetchone()
  151. if row is None:
  152. res["api_comment"] = "user not found"
  153. return res
  154. res["user"]["userid"] = userid
  155. for idx,f in enumerate(user_fields):
  156. res["user"][f] = row[idx]
  157. ## go through each card and fill in card data and pass data
  158. ##
  159. res["card"] = []
  160. query = "select logical_card_id from user_card where userid = %s and active = 1 order by logical_card_id asc"
  161. card_cursor = db.cursor()
  162. card_cursor.execute(query, [userid])
  163. rows = card_cursor.fetchall()
  164. for row in rows:
  165. card_res = CardInfo(db, {"logical_card_id":row[0]})
  166. res["card"].append(card_res)
  167. res["result"] = "success"
  168. return res
  169. def _update_pass_bits(cursor, passid):
  170. q = "select logical_card_id from user_pass where user_pass_id = %s"
  171. cursor.execute(q, [passid])
  172. rows = cursor.fetchall()
  173. print("\n\nupdating pass bits", passid, "\n\n")
  174. cardid = -1
  175. for row in rows:
  176. cardid = row[0]
  177. break
  178. print("\n\nupdating pass bits cardid:", cardid, "\n\n")
  179. if cardid < 0: return
  180. q = "update user_pass set active = 0 where logical_card_id = %s"
  181. cursor.execute(q, [cardid])
  182. q = "update user_pass set active = 1 where logical_card_id = %s and expired = 0 and queue_order = " + \
  183. "( select min(x.queue_order) from user_pass x where x.logical_card_id = %s and x.expired = 0 )"
  184. cursor.execute(q, [cardid,cardid])
  185. ## _ _
  186. ## _ __ _ _| | ___ ___| | __ _ ___ ___
  187. ## | '__| | | | |/ _ \/ __| |/ _` / __/ __|
  188. ## | | | |_| | | __/ (__| | (_| \__ \__ \
  189. ## |_| \__,_|_|\___|\___|_|\__,_|___/___/
  190. ##
  191. def Ruleclass(db, ctx):
  192. res = {}
  193. ruleclass_fields = RULECLASS_FIELDS.copy()
  194. cursor = db.cursor()
  195. fields = ruleclass_fields.copy()
  196. field_vals = []
  197. if ctx["action"] == "search":
  198. query = "select id, rulename, ruleclass from rule_class"
  199. cursor.execute(query)
  200. rows = cursor.fetchall()
  201. res["ruleclass"] = []
  202. for row in rows:
  203. res["ruleclass"].append({"id":row[0], "rulename":row[1], "ruleclass":row[2]})
  204. db.commit()
  205. return res
  206. ##
  207. ## _ __ __ _ ___ ___
  208. ## | '_ \ / _` / __/ __|
  209. ## | |_) | (_| \__ \__ \
  210. ## | .__/ \__,_|___/___/
  211. ## |_|
  212. def Pass(db, ctx):
  213. res = {}
  214. passid = -1
  215. if ("user_pass_id" in ctx):
  216. passid = ctx["user_pass_id"]
  217. pass_fields = PASS_FIELDS.copy()
  218. cursor = db.cursor()
  219. fields = pass_fields.copy()
  220. field_vals = []
  221. if (ctx["action"] == "get"):
  222. query = "select " + ",".join(pass_fields) + " from user_pass where user_pass_id = %s"
  223. cursor.execute(query, [passid])
  224. row = cursor.fetchone()
  225. if row is not None:
  226. res["result"] = "success"
  227. res["user_pass_id"] = passid
  228. for idx,f in enumerate(pass_fields):
  229. if isinstance(row[idx], datetime.datetime):
  230. res[f] = row[idx].strftime("%Y-%m-%d %H:%M:%S")
  231. else:
  232. res[f] = row[idx]
  233. else:
  234. res["result"] = "fail"
  235. res["api_comment"] = "pass not found"
  236. elif (ctx["action"] == "add"):
  237. if (not "logical_card_id" in ctx) or (ctx["logical_card_id"] == ''):
  238. res["result"] = "fail"
  239. res["api_comment"] = "must have logical_card_id to add pass"
  240. else:
  241. ## fill in some default values
  242. ##
  243. dt = time.strftime('%Y-%m-%d %H:%M:%S')
  244. if "issued" not in ctx: ctx["issued"] = dt
  245. if "expired" not in ctx: ctx["expired"] = 0
  246. if "active" not in ctx: ctx["active"] = 0
  247. if "logical_card_id" in ctx:
  248. cardid = ctx["logical_card_id"]
  249. _q = "select queue_order from user_pass where logical_card_id = %s and expired = 0 order by queue_order desc limit 1"
  250. _c = db.cursor()
  251. _c.execute(_q, [cardid])
  252. _r = _c.fetchone()
  253. if _r is not None:
  254. ctx["queue_order"] = int(_r[0])+1
  255. else:
  256. ctx["active"] = 1
  257. ctx["queue_order"] = 0
  258. else:
  259. ctx["queue_order"] = 0
  260. for f in pass_fields:
  261. if f in ctx: field_vals.append(ctx[f])
  262. else: field_vals.append(None)
  263. query = "insert into user_pass (" + ",".join(fields) + ") values (" + ",".join(["%s"]*len(fields)) + ")"
  264. print(query)
  265. print(fields, field_vals)
  266. cursor.execute(query, field_vals)
  267. res["user_pass_id"] = cursor.lastrowid
  268. res["result"] = "success"
  269. _update_pass_bits(cursor, passid);
  270. elif (ctx["action"] == "update"):
  271. update_field = []
  272. update_val = []
  273. for f in pass_fields:
  274. if f in ctx:
  275. update_field.append(f + "= %s")
  276. update_val.append(ctx[f])
  277. update_val.append(passid)
  278. query = "update user_pass set " + ",".join(update_field) + " where user_pass_id = %s"
  279. cursor.execute(query, update_val)
  280. res["user_pass_id"] = passid
  281. res["result"] = "success"
  282. _update_pass_bits(cursor, passid);
  283. elif (ctx["action"] == "deactivate"):
  284. update_field = []
  285. update_val = []
  286. for f in pass_fields:
  287. if f in ctx:
  288. update_field.append(f + "= %s")
  289. update_val.append(ctx[f])
  290. update_val.append(passid)
  291. query = "update user_pass set active = 0, expired = 1 where user_pass_id = %s"
  292. cursor.execute(query, [passid])
  293. _update_pass_bits(cursor, passid);
  294. res["user_pass_id"] = passid
  295. res["result"] = "success"
  296. elif (ctx["action"] == "delete"):
  297. query = "delete from user_pass where user_pass_id = %s"
  298. cursor.execute(query, [passid])
  299. _update_pass_bits(cursor, passid);
  300. res["result"] = "success"
  301. db.commit()
  302. return res
  303. ## _
  304. ## ___ __ _ _ __ __| |
  305. ## / __/ _` | '__/ _` |
  306. ## | (_| (_| | | | (_| |
  307. ## \___\__,_|_| \__,_|
  308. ##
  309. def Card(db, ctx):
  310. card_fields = CARD_FIELDS.copy()
  311. res = {}
  312. cardid = -1
  313. if ("logical_card_id" in ctx):
  314. cardid = ctx["logical_card_id"]
  315. cursor = db.cursor()
  316. fields = card_fields.copy()
  317. field_vals = []
  318. if (ctx["action"] == "get"):
  319. query = "select " + ",".join(card_fields) + " from user_card where logical_card_id = %s"
  320. cursor.execute(query, [cardid])
  321. row = cursor.fetchone()
  322. if row is not None:
  323. res["logical_card_id"] = cardid
  324. for idx,f in enumerate(card_fields):
  325. if isinstance(row[idx], datetime.datetime):
  326. res[f] = row[idx].strftime("%Y-%m-%d %H:%M:%S")
  327. else:
  328. res[f] = row[idx]
  329. res["result"] = "success"
  330. else:
  331. res["result"] = "fail"
  332. res["api_comment"] = "card not found"
  333. elif (ctx["action"] == "add"):
  334. fields.append("active")
  335. for f in card_fields:
  336. if f in ctx: field_vals.append(ctx[f])
  337. else: field_vals.append(None)
  338. field_vals.append(1)
  339. query = "insert into user_card (" + ",".join(fields) + ") values (" + ",".join(["%s"]*len(fields)) + ")"
  340. cursor.execute(query, field_vals)
  341. res["logical_card_id"] = cursor.lastrowid
  342. res["result"] = "success"
  343. elif (ctx["action"] == "update"):
  344. if not "logical_card_id" in ctx:
  345. res["result"] = "fail"
  346. res["api_comment"] = "must supply a logical_card_id"
  347. else:
  348. update_field = []
  349. update_val = []
  350. query_card_id = ctx["logical_card_id"]
  351. cursor.execute("select logical_card_id from user_card where logical_card_id = %s", [query_card_id])
  352. rows = cursor.fetchall()
  353. if len(rows) == 0:
  354. res["result"] = "fail"
  355. res["api_comment"] = "card not found"
  356. else:
  357. print(">>>>", len(rows))
  358. for row in rows:
  359. logical_card_id = row[0]
  360. for f in card_fields:
  361. if f in ctx:
  362. update_field.append(f + "= %s")
  363. update_val.append(ctx[f])
  364. update_val.append(cardid)
  365. query = "update user_card set " + ",".join(update_field) + " where logical_card_id = %s"
  366. cursor.execute(query, update_val)
  367. res["logical_card_id"] = cardid
  368. res["result"] = "success"
  369. elif (ctx["action"] == "delete"):
  370. query = "delete from user_card where logical_card_id = %s"
  371. cursor.execute(query, [cardid])
  372. res["result"] = "success"
  373. elif (ctx["action"] == "search"):
  374. query = "select logical_card_id from user_card where "
  375. n_search = 0
  376. if "logical_card_id" in ctx:
  377. query += " logical_card_id = %s"
  378. field_vals.append( ctx["logical_card_id"])
  379. n_search += 1
  380. if "mag_token" in ctx:
  381. query += " mag_token like %s "
  382. field_vals.append( '%' + ctx["mag_token"] + '%')
  383. n_search += 1
  384. if "rfid_token" in ctx:
  385. if len(field_vals)>0: query += " and "
  386. query += " rfid_token like %s "
  387. field_vals.append( '%' + ctx["rfid_token"] + '%')
  388. n_search += 1
  389. query_limit = " "
  390. if "limit" in ctx:
  391. query_limit = " limit %s "
  392. search_vals.append(ctx["limit"])
  393. query += query_limit
  394. res["logical_card_ids"] = []
  395. if n_search > 0:
  396. cursor.execute(query, field_vals)
  397. rows = cursor.fetchall()
  398. for row in rows:
  399. res["logical_card_ids"].append(row[0])
  400. res["result"] = "success"
  401. db.commit()
  402. return res
  403. ##
  404. ## __ _ _ __ ___ _ _ _ __
  405. ## / _` | '__/ _ \| | | | '_ \
  406. ## | (_| | | | (_) | |_| | |_) |
  407. ## \__, |_| \___/ \__,_| .__/
  408. ## |___/ |_|
  409. def Group(db,ctx):
  410. group_res = { "result":"fail"}
  411. action = "get"
  412. if "action" in ctx:
  413. action = ctx["action"]
  414. cursor = db.cursor()
  415. if action == "get":
  416. group_res["group"] = []
  417. query = "select group_id, group_name from groups order by group_id asc"
  418. cursor.execute(query)
  419. rows = cursor.fetchall()
  420. for row in rows:
  421. group_res["group"].append({"group_id":row[0], "group_name":row[1]})
  422. group_res["result"] = "success"
  423. elif action == "getone":
  424. group_res["group"] = []
  425. query = "select group_id, group_name from groups where group_name = %s "
  426. cursor.execute(query, [ctx["group"]])
  427. row = cursor.fetchone()
  428. if not row:
  429. group_res["result"] = "fail"
  430. group_res["api_comment"] = "invalid group"
  431. else:
  432. group_res["result"] = "success"
  433. group_res["group_id"] = row[0]
  434. elif action == "default":
  435. return Group(db, {"action":"getone", "group":"TEST-ORG"})
  436. db.commit()
  437. return group_res
  438. ##
  439. ## _ _ ___ ___ _ __
  440. ## | | | / __|/ _ \ '__|
  441. ## | |_| \__ \ __/ |
  442. ## \__,_|___/\___|_|
  443. ##
  444. def User(db, ctx):
  445. user_fields = USER_FIELDS.copy()
  446. res = {}
  447. cursor = db.cursor()
  448. fields = user_fields.copy()
  449. user_vals = []
  450. userid = -1
  451. if "userid" in ctx: userid = ctx["userid"]
  452. print("cp.user")
  453. ## USER GET
  454. ##
  455. if (ctx["action"] == "get"):
  456. query = "select " + ",".join(user_fields) + " from users where userid = %s"
  457. cursor.execute(query, [userid])
  458. row = cursor.fetchone()
  459. if row is not None:
  460. res["userid"] = userid
  461. for idx,f in enumerate(user_fields):
  462. if isinstance(row[idx], datetime.datetime):
  463. res[f] = row[idx].strftime("%Y-%m-%d %H:%M:%S")
  464. else:
  465. res[f] = row[idx]
  466. res["result"] = "success"
  467. else:
  468. res["result"] = "fail"
  469. res["api_comment"] = "user not found"
  470. ## USER ADD
  471. ##
  472. elif (ctx["action"] == "add"):
  473. if ((not "password" in ctx) or
  474. (not "username" in ctx) ):
  475. res["api_comment"] = "invalid parameters, need username and password to create account"
  476. res["result"] = "fail"
  477. else:
  478. uname = ctx["username"]
  479. pword = ctx["password"]
  480. fields.append("active")
  481. fields.append("created")
  482. for f in user_fields:
  483. if f in ctx: user_vals.append(ctx[f])
  484. elif f == "passwordhash":
  485. ha = hashlib.sha256()
  486. ha.update(str.encode(uname))
  487. ha.update(str.encode(pword))
  488. user_vals.append(ha.hexdigest())
  489. else: user_vals.append(None)
  490. user_vals.append(1)
  491. user_vals.append(time.strftime('%Y-%m-%d %H:%M:%S'))
  492. query = "insert into users (" + ",".join(fields) + ") values (" + ",".join(["%s"]*len(fields)) + ")"
  493. cursor.execute(query, user_vals)
  494. res["userid"] = cursor.lastrowid
  495. res["result"] = "success"
  496. ## USER UPDATE
  497. ##
  498. elif (ctx["action"] == "update"):
  499. if not "userid" in ctx:
  500. res["result"] = "fail"
  501. res["api_comment"] = "no userid specified"
  502. else:
  503. uname = ''
  504. query = "select username from users where userid = %s";
  505. cursor.execute(query, [userid])
  506. rows = cursor.fetchall()
  507. for row in rows:
  508. uname = row[0]
  509. if uname == '':
  510. res["result"] = "fail"
  511. res["api_comment"] = "could not find username"
  512. else:
  513. update_field = []
  514. update_val = []
  515. print("user_field:", user_fields)
  516. print("ctx:", ctx)
  517. for f in user_fields:
  518. if (f == "passwordhash") and ("password" in ctx):
  519. update_field.append(" passwordhash = %s ")
  520. ha = hashlib.sha256()
  521. ha.update(str.encode(uname))
  522. ha.update(str.encode(ctx["password"]))
  523. update_val.append(ha.hexdigest())
  524. elif f in ctx:
  525. update_field.append(f + "= %s")
  526. update_val.append(ctx[f])
  527. else:
  528. pass
  529. #update_val.append(None)
  530. update_val.append(userid)
  531. if len(update_field) == 0:
  532. print("NOPE")
  533. print("manage_user.update>>>", userid, ":".join(update_field), ":".join(update_val), len(update_field))
  534. query = "update users set " + ",".join(update_field) + " where userid = %s"
  535. print("WTFFF???", query)
  536. cursor.execute(query, update_val)
  537. res["userid"] = userid
  538. res["result"] = "success"
  539. ## USER DELETE
  540. ##
  541. elif (ctx["action"] == "delete"):
  542. query = "delete from users where userid = %s"
  543. cursor.execute(query, [userid])
  544. ## USER SEARCH
  545. ##
  546. elif (ctx["action"] == "search"):
  547. res["userids"] = []
  548. res["userid"] = userid
  549. res["result"] = "success"
  550. search_field = []
  551. search_val = []
  552. for f in user_fields:
  553. if f in ctx:
  554. search_field.append(f + " like %s")
  555. search_val.append('%' + ctx[f] + '%')
  556. query_limit = " "
  557. if "limit" in ctx:
  558. query_limit = " limit %s "
  559. search_val.append(ctx["limit"])
  560. query = "select userid from users where " + " and ".join(search_field) + query_limit
  561. cursor.execute(query, search_val)
  562. rows = cursor.fetchall()
  563. for row in rows:
  564. res["userids"].append(row[0])
  565. db.commit()
  566. return res
  567. ## _ _
  568. ## _ __ ___ ___ _ _ ___| | ___ ___ __ _ _ __ __| |
  569. ## | '__/ _ \/ __| | | |/ __| |/ _ \ / __/ _` | '__/ _` |
  570. ## | | | __/ (__| |_| | (__| | __/ | (_| (_| | | | (_| |
  571. ## |_| \___|\___|\__, |\___|_|\___| \___\__,_|_| \__,_|
  572. ## |___/
  573. def RecycleCard(db, ctx):
  574. res = {"result":"fail"}
  575. cursor = db.cursor()
  576. fields = ["logical_card_id", "rfid_token", "mag_token", "group",
  577. "userid",
  578. "rule", "pass_class", "nrides_remain", "nrides_orig", "nday_orig" ]
  579. val = {}
  580. for f in fields:
  581. if f in ctx:
  582. if ctx[f] and len(ctx[f]) > 0:
  583. val[f] = ctx[f]
  584. if ((not ("logical_card_id" in val)) and
  585. (not ("rfid_token" in val)) and
  586. (not ("mag_token" in val))):
  587. return res
  588. logical_card_id = -1
  589. if not ("logical_card_id" in val):
  590. if "mag_token" in val:
  591. query = "select logical_card_id from user_card where mag_token = %s and active = 1"
  592. cursor.execute(query, [val["mag_token"]])
  593. cid = cursor.fetchone()
  594. if cid is not None:
  595. val["logical_card_id"] = cid[0]
  596. else:
  597. return res
  598. elif "rfid_token" in val:
  599. query = "select logical_card_id from user_card where rfid_token = %s and active = 1"
  600. cursor.execute(query, [val["rfid_token"]])
  601. cid = cursor.fetchone()
  602. if cid is not None:
  603. val["logical_card_id"] = cid[0]
  604. else:
  605. return res
  606. group_info = Group(db, {"action":"default"})
  607. if "group" in val:
  608. group_info = Group(db, {"action":"getone", "group":val["group"]})
  609. if group_info["result"] != "success":
  610. res["api_comment"] = "invalid group"
  611. return res
  612. query = "update user_card set active = 0 where logical_card_id = %s"
  613. cursor.execute(query, [val["logical_card_id"]])
  614. card_info = {"action":"add", "group_id":group_info["group_id"], "active":1}
  615. if "mag_token" in val: card_info["mag_token"] = val["mag_token"]
  616. if "rfid_token" in val: card_info["rfid_token"] = val["rfid_token"]
  617. card_res = Card(db, card_info)
  618. if card_res["result"] != "success":
  619. res["result"] = "fail"
  620. res["api_comment"] = "failed to find card"
  621. return res
  622. res["logical_card_id"] = card_res["logical_card_id"]
  623. if "pass_class" in val:
  624. pass_opt = {"action":"add", "logical_card_id": res["logical_card_id"] }
  625. if val["pass_class"] == "OTHER":
  626. pass_opt["rule"] = val["rule"]
  627. Pass(db, pass_opt)
  628. elif val["pass_class"] == "NRIDE":
  629. pass_opt["rule"] = val["rule"]
  630. pass_opt["nrides_orig"] = val["nrides_orig"]
  631. pass_opt["nrides_remain"] = val["nrides_remain"]
  632. Pass(db, pass_opt)
  633. elif val["pass_class"] == "NDAY":
  634. pass_opt["rule"] = val["rule"]
  635. pass_opt["nday_orig"] = val["nday_orig"]
  636. Pass(db, pass_opt)
  637. return res
  638. ## _
  639. ## ___ ___ __ _ _ __ ___| |__
  640. ## / __|/ _ \/ _` | '__/ __| '_ \
  641. ## \__ \ __/ (_| | | | (__| | | |
  642. ## |___/\___|\__,_|_| \___|_| |_|
  643. ##
  644. def Search(db, ctx):
  645. res = {"result":"fail"}
  646. cursor = db.cursor()
  647. fields = ["search_type", "search_string"]
  648. val = {}
  649. for f in fields:
  650. if f in ctx:
  651. if ctx[f] and len(ctx[f]) > 0:
  652. val[f] = ctx[f]
  653. if val["search_type"] == "card":
  654. t = val["search_string"]
  655. p = '%' + t + '%'
  656. query = "select logical_card_id, mag_token, rfid_token, userid, issued, firstused, lastused, group_id, issuetype"
  657. query += " from user_card where mag_token like %s "
  658. query += " or rfid_token like %s "
  659. query += " or comment like %s "
  660. query += " or issuetype like %s "
  661. cursor.execute(query, [p, p, p, p])
  662. rows = cursor.fetchall()
  663. res["data"] = []
  664. for row in rows:
  665. _d = {
  666. "logical_card_id": row[0],
  667. "mag_token": row[1],
  668. "rfid_token": row[2],
  669. "userid": row[3],
  670. "issued": row[4],
  671. "firstused": row[5],
  672. "lastused": row[6],
  673. "group_id": row[7],
  674. "issuetype": row[8]
  675. }
  676. res["data"].append( _d )
  677. res["result"] = "success"
  678. elif val["search_type"] == "user":
  679. t = val["search_string"]
  680. p = '%' + t + '%'
  681. fields = [ "username", "first_name", "last_name", "phone", "email", "address", "city","state", "zip", "created",
  682. "shipping_address", "shipping_city", "shipping_state", "shipping_zip", "shipping_name",
  683. "shipping_country_code", "shipping_country_name" ]
  684. query = "select userid, " + ", ".join(fields)
  685. query += " from users "
  686. query += " where " + " like %s or ".join(fields) + " like %s "
  687. print("user query:", query)
  688. cursor.execute(query, [p]*len(fields))
  689. rows = cursor.fetchall()
  690. res["data"] = []
  691. for row in rows:
  692. _d = { "userid": row[0] }
  693. for idx,f in enumerate(fields):
  694. _d[f] = row[idx+1]
  695. res["data"].append( _d )
  696. res["result"] = "success"
  697. elif val["search_type"] == "admin":
  698. res["result"] = "success"
  699. return res
  700. ## _ _ _ _ _ _
  701. ## __ _ __| | __| | ___ __ _ _ __ __| | | |__ | | ___ ___| | __
  702. ## / _` |/ _` |/ _` | / __/ _` | '__/ _` | | '_ \| |/ _ \ / __| |/ /
  703. ## | (_| | (_| | (_| | | (_| (_| | | | (_| | | |_) | | (_) | (__| <
  704. ## \__,_|\__,_|\__,_| \___\__,_|_| \__,_| |_.__/|_|\___/ \___|_|\_\
  705. ##
  706. def AddCardBlock(db, ctx):
  707. res = {"result":"fail"}
  708. cursor = db.cursor()
  709. fields = ["mag_token", "rfid_token", "group_id",
  710. "rule", "nday_orig", "nrides_remain", "nrides_orig",
  711. "count",
  712. "pass_rule", "pass_nrides_remain", "pass_nrides_orig",
  713. "pass_nday_orig", "pass_class"]
  714. val = {}
  715. for f in fields:
  716. if f in ctx:
  717. if ctx[f] and len(ctx[f]) > 0:
  718. val[f] = ctx[f]
  719. if not ("count" in val):
  720. res["result"] = "fail"
  721. res["api_comment"] = "count must be positive"
  722. return res
  723. if ((not ("mag_token" in val)) and
  724. (not ("rfid_token" in val))):
  725. res["result"] = "fail"
  726. res["api_comment"] = "mag_token and/or rfid_token must be specified"
  727. return res
  728. use_mag = False
  729. use_rfid = False
  730. if "mag_token" in val:
  731. use_mag = True
  732. pfx_mag_cred = val["mag_token"].split(":")[0]
  733. base_mag_cred = int(val["mag_token"].split(":")[-1])
  734. if "rfid_token" in val:
  735. use_rfid = True
  736. pfx_rfid_cred = ":".join(val["rfid_token"].split(":")[0:2])
  737. base_rfid_cred = int(val["rfid_token"].split(":")[-1])
  738. logical_card_ids = []
  739. for idx in range(int(val["count"])):
  740. card_info = {"action":"add", "group_id":val["group_id"], "active":1}
  741. if "mag_token" in val: card_info["mag_token"] = val["mag_token"]
  742. if "rfid_token" in val: card_info["rfid_token"] = val["rfid_token"]
  743. if use_mag:
  744. card_info["mag_token"] = pfx_mag_cred + ":" + str(base_mag_cred + idx)
  745. if use_rfid:
  746. card_info["rfid_token"] = pfx_rfid_cred + ":" + str(base_rfid_cred + idx)
  747. card_res = Card(db, card_info)
  748. if card_res["result"] != "success":
  749. res["result"] = "fail"
  750. res["api_comment"] = "failed to add card"
  751. return res
  752. logical_card_id = card_res["logical_card_id"]
  753. if "pass_rule" in val:
  754. pass_info = {"action":"add", "logical_card_id":logical_card_id, "active":1,
  755. "rule" : val["pass_rule"] }
  756. if val["pass_class"] == "OTHER":
  757. pass
  758. elif val["pass_class"] == "NRIDE":
  759. pass_info["nrides_remain"] = val["pass_nrides_remain"]
  760. pass_info["nrides_orig"] = val["pass_nrides_orig"]
  761. elif val["pass_class"] == "NDAY":
  762. pass_info["nday_orig"] = val["pass_nday_orig"]
  763. pass_res = Pass(db, pass_info)
  764. logical_card_ids.append(logical_card_id)
  765. res["result"] = "success"
  766. res["logical_card_ids"] = logical_card_ids
  767. return res
  768. ## _
  769. ## _ __ ___ __ _(_)_ __
  770. ## | '_ ` _ \ / _` | | '_ \
  771. ## | | | | | | (_| | | | | |
  772. ## |_| |_| |_|\__,_|_|_| |_|
  773. ##
  774. def main(db):
  775. print("main")
  776. print("---------")
  777. print("---------")
  778. print("---------")
  779. res = User(db, {"action":"add", "username":"abe" })
  780. print("user.add:", res)
  781. res = User(db, {"action":"update", "username":"abeabe", "userid":res["userid"]})
  782. print("user.update:", res)
  783. res = User(db, {"action":"get", "userid":res["userid"]})
  784. print("user.get:", res)
  785. res = User(db, {"action":"delete", "userid": res["userid"]})
  786. print("user.delete:", res)
  787. print("---------")
  788. print("---------")
  789. print("---------")
  790. res = Card(db, {"action":"get", "logical_card_id":1})
  791. print("card.get:", res)
  792. res = Card(db, {"action":"add", "mag_token":"2:1234", "rfid_token":"26:20:415", "comment":"testing api", "userid":1})
  793. print("card.add:", res)
  794. res = Card(db, {"action":"update", "mag_token":"2:9234", "logical_card_id":res["logical_card_id"]})
  795. print("card.update:", res)
  796. res = Card(db, {"action":"delete", "logical_card_id":res["logical_card_id"]})
  797. print("card.delete:", res)
  798. print("---------")
  799. print("---------")
  800. print("---------")
  801. res = Pass(db, {"action":"get", "user_pass_id":11})
  802. print("pass.get:", res)
  803. res = Pass(db, {"action":"add", "logical_card_id":1, "queue_order":9, "rule":"TEST-ORG-NDAY", "nday_orig":3})
  804. print("pass.add:", res)
  805. res = Pass(db, {"action":"update", "user_pass_id":res["user_pass_id"], "queue_order":10, "rule":"TEST-ORG-NDAY", "nday_orig":5})
  806. print("pass.update:", res)
  807. res = Pass(db, {"action":"delete", "user_pass_id":res["user_pass_id"]})
  808. print("pass.delete:", res)
  809. print("---------")
  810. print("---------")
  811. print("---------")
  812. res = UserInfo(db, {"userid":348})
  813. print("userinfo:", json.dumps(res, indent=2))
  814. print("---------")
  815. print("---------")
  816. print("---------")
  817. res = Request({"function":"CardInfo", "action":"search", "logical_card_id":1})
  818. print("request.card.search:", res)
  819. if __name__ == "__main__":
  820. conn = mysql.connector.connect(user=_USER, password=_PASSWORD, host=_HOST, database=_DATABASE, port=_PORT)
  821. main(conn)
  822. conn.close()