import mysql.connector import User def is_in(lst: list, name: str): for i in lst: if (i[0] == name): return (1); return (0); class Database: def __init__(self, host, port, user, password): """ : param host: The ip of the database : type host: str : param port: The port of the database : type port: int : param user: The user to login on the database : type user: str : param password: The password of the user : type password: str """ self.mydb = mysql.connector.connect( host = host, port = port, user = user, password = password, ) self.cursor = self.mydb.cursor() self.cursor.execute("SHOW DATABASES"); if (not is_in(self.cursor, "zeolak")): self.cursor.execute("CREATE DATABASE zeolak") self.mydb = mysql.connector.connect( host = host, port = port, user = user, password = password, database = "zeolak" ) self.cursor = self.mydb.cursor() def _create_table(self, name: str, content: dict): command: str = f"CREATE TABLE {name} (" for key, value in content.items(): command += f"{key} {value}, " command = command[:-2] command += ")" self.cursor.execute(command) def create_user_table(self): self.cursor.execute("SHOW TABLES"); if (not is_in(self.cursor, "users")): data = { "email": "VARCHAR(255)", "username": "VARCHAR(255)", "first_name": "VARCHAR(255)", "last_name": "VARCHAR(255)", "password": "VARCHAR(255)" } self._create_table("users", data) def add_user(self, user: User): if (len(user.password) < 8): return ("Password too short (minimum 8 chars)") if (len(user.first_name) == 0): return ("First name empty") if (len(user.last_name) == 0): return ("Last name empty") if (len(user.username) == 0): return ("Username empty") self.cursor.execute(f"SELECT * FROM `users` WHERE `email` = '{user.email}'") if (len(self.cursor.fetchall())): return ("Email already used") self.cursor.execute(user.to_insert_sql()) self.mydb.commit() def account_test(self, email: str, password: str): self.cursor.execute(f"SELECT * FROM `users` WHERE `email` = '{email}'") result = self.cursor.fetchall() if (len(result) == 0): return (1); if (result[0][-1] != password): return (1); return (0);