Skip to content

Commit

Permalink
added models.py and db.py
Browse files Browse the repository at this point in the history
  • Loading branch information
MattiaCincotta committed Jun 18, 2024
1 parent ec1aa30 commit e9b92b3
Show file tree
Hide file tree
Showing 2 changed files with 121 additions and 0 deletions.
16 changes: 16 additions & 0 deletions server/utils/db.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import mysql.connector
from flask import g, current_app


def getConnection():
if 'db' not in g or not g.db.is_connected():
try:
g.db = mysql.connector.connect(
host=current_app.config['MYSQL_HOST'],
user=current_app.config['MYSQL_USER'],
password=current_app.config['MYSQL_PASSWORD'],
database=current_app.config['MYSQL_DB']
)
except mysql.connector.Error as e:
print(f"Error connecting to MySQL: {e}")
return g.db
105 changes: 105 additions & 0 deletions server/utils/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
import db
from flask import current_app

##################### USER CLASS #####################

class User():

"""
Represents a user in the system.
Attributes:
__id (int): The user's ID.
__username (str): The username of user
__hashPassword (str): The hashed password of the user.
"""

def __init__(self, id: int, username: str, hashPassword: str) -> None:

self.__id = id
self.__username = username
self.__hashPassword = hashPassword


def get_id(self) -> int:
return self.__id

def get_username(self) -> str:
return self.__username

def get_hashPassword(self) -> str:
return self.__hashPassword

################## END OF USER CLASS ##################




#################### USER MANAGER #####################
class UserManager():

@staticmethod
def resultRowToUser(res: tuple) -> User:
return User(res[0], res[1], res[2]) # id, username, password


@staticmethod
def get(id: int | str) -> User | None: #Retrieves a user by their ID.

try:
conn = db.getConnection(current_app)
cursor = conn.cursor()
cursor.execute("SELECT * FROM users WHERE id = %s", (id, ))
res = cursor.fetchone()
if res:
return UserManager.resultRowToUser(res)
except Exception as e:
current_app.logger.error(f"Error fetching user by ID: {e}")
finally:
cursor.close()

return None

@staticmethod
def getByUsername(username: str) -> User | None: #Retrieves a user by their email.

conn = db.getConnection(current_app)
cursor = conn.cursor()

try:
cursor.execute("SELECT * FROM users WHERE username = %s", (username, ))
res = cursor.fetchone()
if res:
return UserManager.resultRowToUser(res)
except Exception as e:
current_app.logger.error(f"Error fetching user by ID: {e}")
finally:
cursor.close()

return None

@staticmethod
def addUser(username: str, hashPassword: str) -> User: #Adds a new user to the database.


conn = db.getConnection(current_app)
cursor = conn.cursor()

try:
if UserManager.getByUsername(username):
return None

cursor.execute("INSERT INTO users (username, password) VALUES (%s, %s)", (username, hashPassword, ))
conn.commit()
added_user = UserManager.getByUsername(username)
assert added_user != None
return added_user

except Exception as e:
current_app.logger.error(f"Error fetching user by ID: {e}")
finally:
cursor.close()

return None

################## END OF USER MANAGER ##################

2 comments on commit e9b92b3

@AlBovo
Copy link
Member

@AlBovo AlBovo commented on e9b92b3 Jun 18, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@MattiaCincotta cosa stai facendo? 💀

@MattiaCincotta
Copy link
Collaborator Author

@MattiaCincotta MattiaCincotta commented on e9b92b3 Jun 18, 2024 via email

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.