You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

105 line
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 = %s")
  32. userid = None
  33. try:
  34. cursor.execute(query, (username,))
  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 = %s")
  55. username = None
  56. try:
  57. cursor.execute(query, (userid,))
  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 = %s and password = %s")
  81. user = None
  82. try:
  83. cursor.execute(query, (username, password))
  84. users = cursor.fetchall()
  85. if len(users):
  86. user = users[0]
  87. except mysql.connector.Error as err:
  88. print("Failed executing query: {}".format(err))
  89. cursor.fetchall()
  90. exit(1)
  91. finally:
  92. cursor.close()
  93. db.close()
  94. return user