PopufareAPI.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894
  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. _conn.close()
  82. return res
  83. ## _ _ __
  84. ## ___ __ _ _ __ __| (_)_ __ / _| ___
  85. ## / __/ _` | '__/ _` | | '_ \| |_ / _ \
  86. ## | (_| (_| | | | (_| | | | | | _| (_) |
  87. ## \___\__,_|_| \__,_|_|_| |_|_| \___/
  88. ##
  89. def CardInfo(db, ctx):
  90. card_res = {}
  91. action = "get"
  92. if "action" in ctx:
  93. action = ctx["action"]
  94. if action == "get":
  95. print("CardInfo:", ctx)
  96. cardid = -1
  97. if "logical_card_id" in ctx:
  98. cardid = ctx["logical_card_id"]
  99. card_res["logical_card_id"] = cardid
  100. card_res = Card(db, {"action":"get", "logical_card_id": cardid})
  101. card_res["pass"] = []
  102. if card_res["result"] == "success":
  103. ## through each of the passes on the card
  104. ##
  105. pass_query = "select user_pass_id from user_pass where logical_card_id = %s and expired = 0 order by queue_order asc"
  106. pass_cursor = db.cursor()
  107. pass_cursor.execute(pass_query, [card_res["logical_card_id"]])
  108. pass_rows = pass_cursor.fetchall()
  109. for pass_row in pass_rows:
  110. pass_res = Pass(db, {"action":"get", "user_pass_id":pass_row[0]})
  111. card_res["pass"].append(pass_res)
  112. card_res["user"] = {}
  113. if ((card_res["userid"] is not None) and (int(card_res["userid"]) >= 0)):
  114. card_res["user"] = User(db, {"action":"get", "userid": card_res["userid"] })
  115. elif action == "search":
  116. card_res["cards"] = []
  117. res_cardid = Card(db, ctx)
  118. for cid in res_cardid["logical_card_ids"]:
  119. _c = CardInfo(db, {"action":"get", "logical_card_id":cid})
  120. card_res["cards"].append(_c)
  121. card_res["result"] = "success"
  122. return card_res
  123. ## _ __
  124. ## _ _ ___ ___ _ __(_)_ __ / _| ___
  125. ## | | | / __|/ _ \ '__| | '_ \| |_ / _ \
  126. ## | |_| \__ \ __/ | | | | | | _| (_) |
  127. ## \__,_|___/\___|_| |_|_| |_|_| \___/
  128. ##
  129. def UserInfo(db, ctx):
  130. res = {}
  131. res["result"] = "fail"
  132. userid = -1
  133. if ("userid" in ctx):
  134. userid = ctx["userid"]
  135. pass_fields = PASS_FIELDS.copy()
  136. card_fields = CARD_FIELDS.copy()
  137. user_fields = USER_FIELDS.copy()
  138. res["userid"] = userid
  139. cursor = db.cursor()
  140. ## fill in user data
  141. ##
  142. res["user"] = {}
  143. fields = USER_FIELDS.copy()
  144. query = "select " + ",".join(fields) + " from users where userid = %s"
  145. cursor.execute(query, [userid])
  146. row = cursor.fetchone()
  147. if row is None:
  148. res["api_comment"] = "user not found"
  149. return res
  150. res["user"]["userid"] = userid
  151. for idx,f in enumerate(user_fields):
  152. res["user"][f] = row[idx]
  153. ## go through each card and fill in card data and pass data
  154. ##
  155. res["card"] = []
  156. query = "select logical_card_id from user_card where userid = %s and active = 1 order by logical_card_id asc"
  157. card_cursor = db.cursor()
  158. card_cursor.execute(query, [userid])
  159. rows = card_cursor.fetchall()
  160. for row in rows:
  161. card_res = CardInfo(db, {"logical_card_id":row[0]})
  162. res["card"].append(card_res)
  163. res["result"] = "success"
  164. return res
  165. def _update_pass_bits(cursor, passid):
  166. q = "select logical_card_id from user_pass where user_pass_id = %s"
  167. cursor.execute(q, [passid])
  168. rows = cursor.fetchall()
  169. print("\n\nupdating pass bits", passid, "\n\n")
  170. cardid = -1
  171. for row in rows:
  172. cardid = row[0]
  173. break
  174. print("\n\nupdating pass bits cardid:", cardid, "\n\n")
  175. if cardid < 0: return
  176. q = "update user_pass set active = 0 where logical_card_id = %s"
  177. cursor.execute(q, [cardid])
  178. q = "update user_pass set active = 1 where logical_card_id = %s and expired = 0 and queue_order = " + \
  179. "( select min(x.queue_order) from user_pass x where x.logical_card_id = %s and x.expired = 0 )"
  180. cursor.execute(q, [cardid,cardid])
  181. ## _ _
  182. ## _ __ _ _| | ___ ___| | __ _ ___ ___
  183. ## | '__| | | | |/ _ \/ __| |/ _` / __/ __|
  184. ## | | | |_| | | __/ (__| | (_| \__ \__ \
  185. ## |_| \__,_|_|\___|\___|_|\__,_|___/___/
  186. ##
  187. def Ruleclass(db, ctx):
  188. res = {}
  189. ruleclass_fields = RULECLASS_FIELDS.copy()
  190. cursor = db.cursor()
  191. fields = ruleclass_fields.copy()
  192. field_vals = []
  193. if ctx["action"] == "search":
  194. query = "select id, rulename, ruleclass from rule_class"
  195. cursor.execute(query)
  196. rows = cursor.fetchall()
  197. res["ruleclass"] = []
  198. for row in rows:
  199. res["ruleclass"].append({"id":row[0], "rulename":row[1], "ruleclass":row[2]})
  200. db.commit()
  201. return res
  202. ##
  203. ## _ __ __ _ ___ ___
  204. ## | '_ \ / _` / __/ __|
  205. ## | |_) | (_| \__ \__ \
  206. ## | .__/ \__,_|___/___/
  207. ## |_|
  208. def Pass(db, ctx):
  209. res = {}
  210. passid = -1
  211. if ("user_pass_id" in ctx):
  212. passid = ctx["user_pass_id"]
  213. pass_fields = PASS_FIELDS.copy()
  214. cursor = db.cursor()
  215. fields = pass_fields.copy()
  216. field_vals = []
  217. if (ctx["action"] == "get"):
  218. query = "select " + ",".join(pass_fields) + " from user_pass where user_pass_id = %s"
  219. cursor.execute(query, [passid])
  220. row = cursor.fetchone()
  221. if row is not None:
  222. res["result"] = "success"
  223. res["user_pass_id"] = passid
  224. for idx,f in enumerate(pass_fields):
  225. if isinstance(row[idx], datetime.datetime):
  226. res[f] = row[idx].strftime("%Y-%m-%d %H:%M:%S")
  227. else:
  228. res[f] = row[idx]
  229. else:
  230. res["result"] = "fail"
  231. res["api_comment"] = "pass not found"
  232. elif (ctx["action"] == "add"):
  233. if (not "logical_card_id" in ctx) or (ctx["logical_card_id"] == ''):
  234. res["result"] = "fail"
  235. res["api_comment"] = "must have logical_card_id to add pass"
  236. else:
  237. ## fill in some default values
  238. ##
  239. dt = time.strftime('%Y-%m-%d %H:%M:%S')
  240. if "issued" not in ctx: ctx["issued"] = dt
  241. if "expired" not in ctx: ctx["expired"] = 0
  242. if "active" not in ctx: ctx["active"] = 0
  243. if "logical_card_id" in ctx:
  244. cardid = ctx["logical_card_id"]
  245. _q = "select queue_order from user_pass where logical_card_id = %s and expired = 0 order by queue_order desc limit 1"
  246. _c = db.cursor()
  247. _c.execute(_q, [cardid])
  248. _r = _c.fetchone()
  249. if _r is not None:
  250. ctx["queue_order"] = int(_r[0])+1
  251. else:
  252. ctx["active"] = 1
  253. ctx["queue_order"] = 0
  254. else:
  255. ctx["queue_order"] = 0
  256. for f in pass_fields:
  257. if f in ctx: field_vals.append(ctx[f])
  258. else: field_vals.append(None)
  259. query = "insert into user_pass (" + ",".join(fields) + ") values (" + ",".join(["%s"]*len(fields)) + ")"
  260. print(query)
  261. print(fields, field_vals)
  262. cursor.execute(query, field_vals)
  263. res["user_pass_id"] = cursor.lastrowid
  264. res["result"] = "success"
  265. _update_pass_bits(cursor, passid);
  266. elif (ctx["action"] == "update"):
  267. update_field = []
  268. update_val = []
  269. for f in pass_fields:
  270. if f in ctx:
  271. update_field.append(f + "= %s")
  272. update_val.append(ctx[f])
  273. update_val.append(passid)
  274. query = "update user_pass set " + ",".join(update_field) + " where user_pass_id = %s"
  275. cursor.execute(query, update_val)
  276. res["user_pass_id"] = passid
  277. res["result"] = "success"
  278. _update_pass_bits(cursor, passid);
  279. elif (ctx["action"] == "deactivate"):
  280. update_field = []
  281. update_val = []
  282. for f in pass_fields:
  283. if f in ctx:
  284. update_field.append(f + "= %s")
  285. update_val.append(ctx[f])
  286. update_val.append(passid)
  287. query = "update user_pass set active = 0, expired = 1 where user_pass_id = %s"
  288. cursor.execute(query, [passid])
  289. _update_pass_bits(cursor, passid);
  290. res["user_pass_id"] = passid
  291. res["result"] = "success"
  292. elif (ctx["action"] == "delete"):
  293. query = "delete from user_pass where user_pass_id = %s"
  294. cursor.execute(query, [passid])
  295. _update_pass_bits(cursor, passid);
  296. res["result"] = "success"
  297. db.commit()
  298. return res
  299. ## _
  300. ## ___ __ _ _ __ __| |
  301. ## / __/ _` | '__/ _` |
  302. ## | (_| (_| | | | (_| |
  303. ## \___\__,_|_| \__,_|
  304. ##
  305. def Card(db, ctx):
  306. card_fields = CARD_FIELDS.copy()
  307. res = {}
  308. cardid = -1
  309. if ("logical_card_id" in ctx):
  310. cardid = ctx["logical_card_id"]
  311. cursor = db.cursor()
  312. fields = card_fields.copy()
  313. field_vals = []
  314. if (ctx["action"] == "get"):
  315. query = "select " + ",".join(card_fields) + " from user_card where logical_card_id = %s"
  316. cursor.execute(query, [cardid])
  317. row = cursor.fetchone()
  318. if row is not None:
  319. res["logical_card_id"] = cardid
  320. for idx,f in enumerate(card_fields):
  321. if isinstance(row[idx], datetime.datetime):
  322. res[f] = row[idx].strftime("%Y-%m-%d %H:%M:%S")
  323. else:
  324. res[f] = row[idx]
  325. res["result"] = "success"
  326. else:
  327. res["result"] = "fail"
  328. res["api_comment"] = "card not found"
  329. elif (ctx["action"] == "add"):
  330. fields.append("active")
  331. for f in card_fields:
  332. if f in ctx: field_vals.append(ctx[f])
  333. else: field_vals.append(None)
  334. field_vals.append(1)
  335. query = "insert into user_card (" + ",".join(fields) + ") values (" + ",".join(["%s"]*len(fields)) + ")"
  336. cursor.execute(query, field_vals)
  337. res["logical_card_id"] = cursor.lastrowid
  338. res["result"] = "success"
  339. elif (ctx["action"] == "update"):
  340. if not "logical_card_id" in ctx:
  341. res["result"] = "fail"
  342. res["api_comment"] = "must supply a logical_card_id"
  343. else:
  344. update_field = []
  345. update_val = []
  346. query_card_id = ctx["logical_card_id"]
  347. cursor.execute("select logical_card_id from user_card where logical_card_id = %s", [query_card_id])
  348. rows = cursor.fetchall()
  349. if len(rows) == 0:
  350. res["result"] = "fail"
  351. res["api_comment"] = "card not found"
  352. else:
  353. print(">>>>", len(rows))
  354. for row in rows:
  355. logical_card_id = row[0]
  356. for f in card_fields:
  357. if f in ctx:
  358. update_field.append(f + "= %s")
  359. update_val.append(ctx[f])
  360. update_val.append(cardid)
  361. query = "update user_card set " + ",".join(update_field) + " where logical_card_id = %s"
  362. cursor.execute(query, update_val)
  363. res["logical_card_id"] = cardid
  364. res["result"] = "success"
  365. elif (ctx["action"] == "delete"):
  366. query = "delete from user_card where logical_card_id = %s"
  367. cursor.execute(query, [cardid])
  368. res["result"] = "success"
  369. elif (ctx["action"] == "search"):
  370. query = "select logical_card_id from user_card where "
  371. n_search = 0
  372. if "logical_card_id" in ctx:
  373. query += " logical_card_id = %s"
  374. field_vals.append( ctx["logical_card_id"])
  375. n_search += 1
  376. if "mag_token" in ctx:
  377. query += " mag_token like %s "
  378. field_vals.append( '%' + ctx["mag_token"] + '%')
  379. n_search += 1
  380. if "rfid_token" in ctx:
  381. if len(field_vals)>0: query += " and "
  382. query += " rfid_token like %s "
  383. field_vals.append( '%' + ctx["rfid_token"] + '%')
  384. n_search += 1
  385. query_limit = " "
  386. if "limit" in ctx:
  387. query_limit = " limit %s "
  388. search_vals.append(ctx["limit"])
  389. query += query_limit
  390. res["logical_card_ids"] = []
  391. if n_search > 0:
  392. cursor.execute(query, field_vals)
  393. rows = cursor.fetchall()
  394. for row in rows:
  395. res["logical_card_ids"].append(row[0])
  396. res["result"] = "success"
  397. db.commit()
  398. return res
  399. ##
  400. ## __ _ _ __ ___ _ _ _ __
  401. ## / _` | '__/ _ \| | | | '_ \
  402. ## | (_| | | | (_) | |_| | |_) |
  403. ## \__, |_| \___/ \__,_| .__/
  404. ## |___/ |_|
  405. def Group(db,ctx):
  406. group_res = { "result":"fail"}
  407. action = "get"
  408. if "action" in ctx:
  409. action = ctx["action"]
  410. cursor = db.cursor()
  411. if action == "get":
  412. group_res["group"] = []
  413. query = "select group_id, group_name from groups order by group_id asc"
  414. cursor.execute(query)
  415. rows = cursor.fetchall()
  416. for row in rows:
  417. group_res["group"].append({"group_id":row[0], "group_name":row[1]})
  418. group_res["result"] = "success"
  419. elif action == "getone":
  420. group_res["group"] = []
  421. query = "select group_id, group_name from groups where group_name = %s "
  422. cursor.execute(query, [ctx["group"]])
  423. row = cursor.fetchone()
  424. if not row:
  425. group_res["result"] = "fail"
  426. group_res["api_comment"] = "invalid group"
  427. else:
  428. group_res["result"] = "success"
  429. group_res["group_id"] = row[0]
  430. elif action == "default":
  431. return Group(db, {"action":"getone", "group":"TEST-ORG"})
  432. db.commit()
  433. return group_res
  434. ##
  435. ## _ _ ___ ___ _ __
  436. ## | | | / __|/ _ \ '__|
  437. ## | |_| \__ \ __/ |
  438. ## \__,_|___/\___|_|
  439. ##
  440. def User(db, ctx):
  441. user_fields = USER_FIELDS.copy()
  442. res = {}
  443. cursor = db.cursor()
  444. fields = user_fields.copy()
  445. user_vals = []
  446. userid = -1
  447. if "userid" in ctx: userid = ctx["userid"]
  448. print("cp.user")
  449. ## USER GET
  450. ##
  451. if (ctx["action"] == "get"):
  452. query = "select " + ",".join(user_fields) + " from users where userid = %s"
  453. cursor.execute(query, [userid])
  454. row = cursor.fetchone()
  455. if row is not None:
  456. res["userid"] = userid
  457. for idx,f in enumerate(user_fields):
  458. if isinstance(row[idx], datetime.datetime):
  459. res[f] = row[idx].strftime("%Y-%m-%d %H:%M:%S")
  460. else:
  461. res[f] = row[idx]
  462. res["result"] = "success"
  463. else:
  464. res["result"] = "fail"
  465. res["api_comment"] = "user not found"
  466. ## USER ADD
  467. ##
  468. elif (ctx["action"] == "add"):
  469. if ((not "password" in ctx) or
  470. (not "username" in ctx) ):
  471. res["api_comment"] = "invalid parameters, need username and password to create account"
  472. res["result"] = "fail"
  473. else:
  474. uname = ctx["username"]
  475. pword = ctx["password"]
  476. fields.append("active")
  477. fields.append("created")
  478. for f in user_fields:
  479. if f in ctx: user_vals.append(ctx[f])
  480. elif f == "passwordhash":
  481. ha = hashlib.sha256()
  482. ha.update(str.encode(uname))
  483. ha.update(str.encode(pword))
  484. user_vals.append(ha.hexdigest())
  485. else: user_vals.append(None)
  486. user_vals.append(1)
  487. user_vals.append(time.strftime('%Y-%m-%d %H:%M:%S'))
  488. query = "insert into users (" + ",".join(fields) + ") values (" + ",".join(["%s"]*len(fields)) + ")"
  489. cursor.execute(query, user_vals)
  490. res["userid"] = cursor.lastrowid
  491. res["result"] = "success"
  492. ## USER UPDATE
  493. ##
  494. elif (ctx["action"] == "update"):
  495. if not "userid" in ctx:
  496. res["result"] = "fail"
  497. res["api_comment"] = "no userid specified"
  498. else:
  499. uname = ''
  500. query = "select username from users where userid = %s";
  501. cursor.execute(query, [userid])
  502. rows = cursor.fetchall()
  503. for row in rows:
  504. uname = row[0]
  505. if uname == '':
  506. res["result"] = "fail"
  507. res["api_comment"] = "could not find username"
  508. else:
  509. update_field = []
  510. update_val = []
  511. print("user_field:", user_fields)
  512. print("ctx:", ctx)
  513. for f in user_fields:
  514. if (f == "passwordhash") and ("password" in ctx):
  515. update_field.append(" passwordhash = %s ")
  516. ha = hashlib.sha256()
  517. ha.update(str.encode(uname))
  518. ha.update(str.encode(ctx["password"]))
  519. update_val.append(ha.hexdigest())
  520. elif f in ctx:
  521. update_field.append(f + "= %s")
  522. update_val.append(ctx[f])
  523. else:
  524. pass
  525. #update_val.append(None)
  526. update_val.append(userid)
  527. if len(update_field) == 0:
  528. print("NOPE")
  529. print("manage_user.update>>>", userid, ":".join(update_field), ":".join(update_val), len(update_field))
  530. query = "update users set " + ",".join(update_field) + " where userid = %s"
  531. print("WTFFF???", query)
  532. cursor.execute(query, update_val)
  533. res["userid"] = userid
  534. res["result"] = "success"
  535. ## USER DELETE
  536. ##
  537. elif (ctx["action"] == "delete"):
  538. query = "delete from users where userid = %s"
  539. cursor.execute(query, [userid])
  540. ## USER SEARCH
  541. ##
  542. elif (ctx["action"] == "search"):
  543. res["userids"] = []
  544. res["userid"] = userid
  545. res["result"] = "success"
  546. search_field = []
  547. search_val = []
  548. for f in user_fields:
  549. if f in ctx:
  550. search_field.append(f + " like %s")
  551. search_val.append('%' + ctx[f] + '%')
  552. query_limit = " "
  553. if "limit" in ctx:
  554. query_limit = " limit %s "
  555. search_val.append(ctx["limit"])
  556. query = "select userid from users where " + " and ".join(search_field) + query_limit
  557. cursor.execute(query, search_val)
  558. rows = cursor.fetchall()
  559. for row in rows:
  560. res["userids"].append(row[0])
  561. db.commit()
  562. return res
  563. ## _ _
  564. ## _ __ ___ ___ _ _ ___| | ___ ___ __ _ _ __ __| |
  565. ## | '__/ _ \/ __| | | |/ __| |/ _ \ / __/ _` | '__/ _` |
  566. ## | | | __/ (__| |_| | (__| | __/ | (_| (_| | | | (_| |
  567. ## |_| \___|\___|\__, |\___|_|\___| \___\__,_|_| \__,_|
  568. ## |___/
  569. def RecycleCard(db, ctx):
  570. res = {"result":"fail"}
  571. cursor = db.cursor()
  572. fields = ["logical_card_id", "rfid_token", "mag_token", "group",
  573. "userid",
  574. "rule", "pass_class", "nrides_remain", "nrides_orig", "nday_orig" ]
  575. val = {}
  576. for f in fields:
  577. if f in ctx:
  578. if ctx[f] and len(ctx[f]) > 0:
  579. val[f] = ctx[f]
  580. if ((not ("logical_card_id" in val)) and
  581. (not ("rfid_token" in val)) and
  582. (not ("mag_token" in val))):
  583. return res
  584. logical_card_id = -1
  585. if not ("logical_card_id" in val):
  586. if "mag_token" in val:
  587. query = "select logical_card_id from user_card where mag_token = %s and active = 1"
  588. cursor.execute(query, [val["mag_token"]])
  589. cid = cursor.fetchone()
  590. if cid is not None:
  591. val["logical_card_id"] = cid[0]
  592. else:
  593. return res
  594. elif "rfid_token" in val:
  595. query = "select logical_card_id from user_card where rfid_token = %s and active = 1"
  596. cursor.execute(query, [val["rfid_token"]])
  597. cid = cursor.fetchone()
  598. if cid is not None:
  599. val["logical_card_id"] = cid[0]
  600. else:
  601. return res
  602. group_info = Group(db, {"action":"default"})
  603. if "group" in val:
  604. group_info = Group(db, {"action":"getone", "group":val["group"]})
  605. if group_info["result"] != "success":
  606. res["api_comment"] = "invalid group"
  607. return res
  608. query = "update user_card set active = 0 where logical_card_id = %s"
  609. cursor.execute(query, [val["logical_card_id"]])
  610. card_info = {"action":"add", "group_id":group_info["group_id"], "active":1}
  611. if "mag_token" in val: card_info["mag_token"] = val["mag_token"]
  612. if "rfid_token" in val: card_info["rfid_token"] = val["rfid_token"]
  613. card_res = Card(db, card_info)
  614. if card_res["result"] != "success":
  615. res["result"] = "fail"
  616. res["api_comment"] = "failed to find card"
  617. return res
  618. res["logical_card_id"] = card_res["logical_card_id"]
  619. if "pass_class" in val:
  620. pass_opt = {"action":"add", "logical_card_id": res["logical_card_id"] }
  621. if val["pass_class"] == "OTHER":
  622. pass_opt["rule"] = val["rule"]
  623. Pass(db, pass_opt)
  624. elif val["pass_class"] == "NRIDE":
  625. pass_opt["rule"] = val["rule"]
  626. pass_opt["nrides_orig"] = val["nrides_orig"]
  627. pass_opt["nrides_remain"] = val["nrides_remain"]
  628. Pass(db, pass_opt)
  629. elif val["pass_class"] == "NDAY":
  630. pass_opt["rule"] = val["rule"]
  631. pass_opt["nday_orig"] = val["nday_orig"]
  632. Pass(db, pass_opt)
  633. return res
  634. ## _
  635. ## _ __ ___ __ _(_)_ __
  636. ## | '_ ` _ \ / _` | | '_ \
  637. ## | | | | | | (_| | | | | |
  638. ## |_| |_| |_|\__,_|_|_| |_|
  639. ##
  640. def main(db):
  641. print("main")
  642. print("---------")
  643. print("---------")
  644. print("---------")
  645. res = User(db, {"action":"add", "username":"abe" })
  646. print("user.add:", res)
  647. res = User(db, {"action":"update", "username":"abeabe", "userid":res["userid"]})
  648. print("user.update:", res)
  649. res = User(db, {"action":"get", "userid":res["userid"]})
  650. print("user.get:", res)
  651. res = User(db, {"action":"delete", "userid": res["userid"]})
  652. print("user.delete:", res)
  653. print("---------")
  654. print("---------")
  655. print("---------")
  656. res = Card(db, {"action":"get", "logical_card_id":1})
  657. print("card.get:", res)
  658. res = Card(db, {"action":"add", "mag_token":"2:1234", "rfid_token":"26:20:415", "comment":"testing api", "userid":1})
  659. print("card.add:", res)
  660. res = Card(db, {"action":"update", "mag_token":"2:9234", "logical_card_id":res["logical_card_id"]})
  661. print("card.update:", res)
  662. res = Card(db, {"action":"delete", "logical_card_id":res["logical_card_id"]})
  663. print("card.delete:", res)
  664. print("---------")
  665. print("---------")
  666. print("---------")
  667. res = Pass(db, {"action":"get", "user_pass_id":11})
  668. print("pass.get:", res)
  669. res = Pass(db, {"action":"add", "logical_card_id":1, "queue_order":9, "rule":"TEST-ORG-NDAY", "nday_orig":3})
  670. print("pass.add:", res)
  671. res = Pass(db, {"action":"update", "user_pass_id":res["user_pass_id"], "queue_order":10, "rule":"TEST-ORG-NDAY", "nday_orig":5})
  672. print("pass.update:", res)
  673. res = Pass(db, {"action":"delete", "user_pass_id":res["user_pass_id"]})
  674. print("pass.delete:", res)
  675. print("---------")
  676. print("---------")
  677. print("---------")
  678. res = UserInfo(db, {"userid":348})
  679. print("userinfo:", json.dumps(res, indent=2))
  680. print("---------")
  681. print("---------")
  682. print("---------")
  683. res = Request({"function":"CardInfo", "action":"search", "logical_card_id":1})
  684. print("request.card.search:", res)
  685. if __name__ == "__main__":
  686. conn = mysql.connector.connect(user=_USER, password=_PASSWORD, host=_HOST, database=_DATABASE, port=_PORT)
  687. main(conn)
  688. conn.close()