from models.database import db import mysql.connector def get_user(username): """ Get the user with the given username :param username: The username :type username: str :return: user """ db.connect() cursor = db.cursor() query = ("SELECT userid, username, password, login_attempts, last_login_attempt from users where username = %s") user = None try: cursor.execute(query, (username,)) users = cursor.fetchall() if len(users): user = users[0] except mysql.connector.Error as err: print("Failed executing query: {}".format(err)) cursor.fetchall() exit(1) finally: cursor.close() db.close() return user def get_users(): """ Retreive all registrered users from the database :return: users """ db.connect() cursor = db.cursor() query = ("SELECT userid, username from users") try: cursor.execute(query) users = cursor.fetchall() except mysql.connector.Error as err: print("Failed executing query: {}".format(err)) users = [] cursor.fetchall() exit(1) finally: cursor.close() db.close() return users def set_login_attempts(userid, num, timestamp): """ Set the number and timestamp of the failed login attempts for the given user. """ db.connect() cursor = db.cursor() query = ("UPDATE users SET login_attempts = %s, last_login_attempt = %s WHERE userid = %s") try: cursor.execute(query, (num, timestamp, userid)) db.commit() except mysql.connector.Error as err: print("Failed executing query: {}".format(err)) cursor.fetchall() exit(1) finally: cursor.close() db.close() def get_user_id_by_name(username): """ Get the id of the unique username :param username: Name of the user :return: The id of the user """ db.connect() cursor = db.cursor() query = ("SELECT userid from users WHERE username = %s") userid = None try: cursor.execute(query, (username,)) users = cursor.fetchall() if(len(users)): userid = users[0][0] except mysql.connector.Error as err: print("Failed executing query: {}".format(err)) cursor.fetchall() exit(1) finally: cursor.close() db.close() return userid def get_user_name_by_id(userid): """ Get username from user id :param userid: The id of the user :return: The name of the user """ db.connect() cursor = db.cursor() query = ("SELECT username from users WHERE userid = %s") username = None try: cursor.execute(query, (userid,)) users = cursor.fetchall() if len(users): username = users[0][0] except mysql.connector.Error as err: print("Failed executing query: {}".format(err)) cursor.fetchall() exit(1) finally: cursor.close() db.close() return username