2023-05-15 04:28:05 +02:00
|
|
|
from uuid import uuid4
|
|
|
|
|
|
|
|
import mysql.connector
|
|
|
|
|
|
|
|
class Database:
|
|
|
|
def __init__(self, app):
|
|
|
|
self.db = mysql.connector.connect(
|
|
|
|
host=app.config["DB_HOSTNAME"],
|
|
|
|
user=app.config["DB_USERNAME"],
|
|
|
|
password=app.config["DB_PASSWORD"],
|
|
|
|
database=app.config["DB_DATABASE"]
|
|
|
|
)
|
|
|
|
|
|
|
|
def delete_old_sessions(self):
|
|
|
|
cursor = self.db.cursor()
|
|
|
|
cursor.execute("DELETE FROM sessions WHERE expiry_date <= CURRENT_TIMESTAMP")
|
|
|
|
self.db.commit()
|
|
|
|
|
|
|
|
def create_session(self, username, password):
|
|
|
|
cursor = self.db.cursor()
|
|
|
|
cursor.execute("SELECT user_id FROM utilisateurs WHERE username=%s AND password=%s", (username, password))
|
|
|
|
|
|
|
|
if result := cursor.fetchall():
|
|
|
|
user_id = result[0][0]
|
|
|
|
else:
|
|
|
|
return None
|
|
|
|
|
|
|
|
uuid = str(uuid4())
|
|
|
|
cursor.execute("INSERT INTO sessions (session_id, user_id) VALUES (%s, %s)", (uuid, user_id))
|
|
|
|
self.db.commit()
|
|
|
|
|
|
|
|
return uuid
|
|
|
|
|
|
|
|
def destroy_session(self, uuid):
|
|
|
|
cursor = self.db.cursor()
|
|
|
|
cursor.execute("DELETE FROM sessions WHERE session_id=%s", (uuid,))
|
|
|
|
self.db.commit()
|
|
|
|
|
|
|
|
def check_connection(self, uuid):
|
|
|
|
cursor = self.db.cursor()
|
|
|
|
cursor.execute("SELECT session_id FROM sessions WHERE session_id=%s", (uuid,))
|
|
|
|
|
|
|
|
return cursor.fetchall()
|
|
|
|
|
|
|
|
class User:
|
|
|
|
def __init__(self, user_id, username, nom, prenom, creation_date):
|
|
|
|
self.id = user_id
|
|
|
|
self.username = username
|
|
|
|
self.nom = nom
|
|
|
|
self.prenom = prenom
|
|
|
|
self.creation_date = creation_date
|
|
|
|
|
|
|
|
class Session:
|
|
|
|
def __init__(self, db, uuid):
|
|
|
|
self.db = db
|
|
|
|
self.uuid = uuid
|
|
|
|
self.user = self.get_user()
|
|
|
|
|
|
|
|
def get_user(self):
|
|
|
|
cursor = self.db.db.cursor()
|
|
|
|
cursor.execute("SELECT utilisateurs.user_id, username, nom, prenom, creation_date FROM utilisateurs "
|
|
|
|
"JOIN sessions ON utilisateurs.user_id=sessions.user_id WHERE session_id=%s", (self.uuid,))
|
2023-05-15 04:31:32 +02:00
|
|
|
result = cursor.fetchall()
|
|
|
|
return User(*result[0])
|