選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

102 行
2.6KB

  1. from models.database import db
  2. import mysql.connector
  3. def get_users():
  4. """
  5. Retreive all registrered users from the database
  6. :return: users
  7. """
  8. db.connect()
  9. cursor = db.cursor()
  10. query = ("SELECT userid, username from users")
  11. try:
  12. cursor.execute(query)
  13. users = cursor.fetchall()
  14. except mysql.connector.Error as err:
  15. print("Failed executing query: {}".format(err))
  16. users = []
  17. cursor.fetchall()
  18. exit(1)
  19. finally:
  20. cursor.close()
  21. db.close()
  22. return users
  23. def get_user_id_by_name(username):
  24. """
  25. Get the id of the unique username
  26. :param username: Name of the user
  27. :return: The id of the user
  28. """
  29. db.connect()
  30. cursor = db.cursor()
  31. query = ("SELECT userid from users WHERE username =\"" + username + "\"")
  32. userid = None
  33. try:
  34. cursor.execute(query)
  35. users = cursor.fetchall()
  36. if(len(users)):
  37. userid = users[0][0]
  38. except mysql.connector.Error as err:
  39. print("Failed executing query: {}".format(err))
  40. cursor.fetchall()
  41. exit(1)
  42. finally:
  43. cursor.close()
  44. db.close()
  45. return userid
  46. def get_user_name_by_id(userid):
  47. """
  48. Get username from user id
  49. :param userid: The id of the user
  50. :return: The name of the user
  51. """
  52. db.connect()
  53. cursor = db.cursor()
  54. query = ("SELECT username from users WHERE userid =\"" + userid + "\"")
  55. username = None
  56. try:
  57. cursor.execute(query)
  58. users = cursor.fetchall()
  59. if len(users):
  60. username = users[0][0]
  61. except mysql.connector.Error as err:
  62. print("Failed executing query: {}".format(err))
  63. cursor.fetchall()
  64. exit(1)
  65. finally:
  66. cursor.close()
  67. db.close()
  68. return username
  69. def match_user(username, password):
  70. """
  71. Check if user credentials are correct, return if exists
  72. :param username: The user attempting to authenticate
  73. :param password: The corresponding password
  74. :type username: str
  75. :type password: str
  76. :return: user
  77. """
  78. db.connect()
  79. cursor = db.cursor()
  80. query = ("SELECT userid, username from users where username = \"" + username +
  81. "\" and password = \"" + password + "\"")
  82. user = None
  83. try:
  84. cursor.execute(query)
  85. users = cursor.fetchall()
  86. if len(users):
  87. user = users[0]
  88. except mysql.connector.Error as err:
  89. print("Failed executing query: {}".format(err))
  90. cursor.fetchall()
  91. exit(1)
  92. finally:
  93. cursor.close()
  94. db.close()
  95. return user