Use try ... with statements everywhere

This commit is contained in:
Thastertyn 2024-03-10 22:58:04 +01:00
parent 031ed358f1
commit afc9db32e4
2 changed files with 66 additions and 49 deletions

View File

@ -12,8 +12,6 @@ db_connection = mysql.connector.connect(
database=MySqlConfig.MYSQL_DATABASE, database=MySqlConfig.MYSQL_DATABASE,
) )
db_cursor = db_connection.cursor(dictionary=True)
jwt_redis_blocklist = redis.StrictRedis( jwt_redis_blocklist = redis.StrictRedis(
host=RedisConfig.REDIS_HOST, host=RedisConfig.REDIS_HOST,
port=RedisConfig.REDIS_PORT, port=RedisConfig.REDIS_PORT,

View File

@ -6,7 +6,7 @@ from typing import Tuple, Union
from mysql.connector import Error from mysql.connector import Error
from flask_jwt_extended import create_access_token from flask_jwt_extended import create_access_token
from app.extensions import db_cursor, db_connection from app.extensions import db_connection
from app.extensions import jwt_redis_blocklist from app.extensions import jwt_redis_blocklist
from app.mail_utils import send_mail from app.mail_utils import send_mail
@ -40,6 +40,7 @@ class UserService:
:rtype: Tuple[Union[dict, str], int] :rtype: Tuple[Union[dict, str], int]
""" """
try:
if not UserService.__verify_username(username): if not UserService.__verify_username(username):
return {"Failed": "Failed to verify username. Try another username"}, 400 return {"Failed": "Failed to verify username. Try another username"}, 400
@ -54,8 +55,8 @@ class UserService:
hashed_password = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt()) hashed_password = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt())
try: with db_connection.cursor() as cursor:
db_cursor.execute("insert into user (username, displayname, email, password) values (%s, %s, %s, %s)", (username, displayname, email, hashed_password)) cursor.execute("insert into user (username, displayname, email, password) values (%s, %s, %s, %s)", (username, displayname, email, hashed_password))
db_connection.commit() db_connection.commit()
except Error as e: except Error as e:
print(f"Error: {e}") print(f"Error: {e}")
@ -80,8 +81,10 @@ class UserService:
:return: Tuple containing a dictionary with a token and an HTTP status code. :return: Tuple containing a dictionary with a token and an HTTP status code.
:rtype: Tuple[Union[dict, str], int] :rtype: Tuple[Union[dict, str], int]
""" """
try:
with db_connection.cursor(dictionary=True) as cursor:
db_cursor.execute("select id, password from user where username = %s", (username,)) cursor.execute("select id, password from user where username = %s", (username,))
result = db_cursor.fetchone() result = db_cursor.fetchone()
user_id = result['id'] user_id = result['id']
@ -99,6 +102,9 @@ class UserService:
return {"token": token}, 200 return {"token": token}, 200
except Error as e:
return {"Failed": f"Failed to login. Error: {e}"}, 500
@staticmethod @staticmethod
def logout(jti, exp) -> Tuple[Union[dict, str], int]: def logout(jti, exp) -> Tuple[Union[dict, str], int]:
""" """
@ -117,8 +123,18 @@ class UserService:
@staticmethod @staticmethod
def delete_user(user_id: str) -> Tuple[Union[dict, str], int]: def delete_user(user_id: str) -> Tuple[Union[dict, str], int]:
"""
Deletes a user account.
:param user_id: User ID.
:type user_id: str
:return: Tuple containing a dictionary and an HTTP status code.
:rtype: Tuple[Union[dict, str], int]
"""
try: try:
db_cursor.execute("delete from user where id = %s", (user_id,)) with db_connection.cursor() as cursor:
cursor.execute("delete from user where id = %s", (user_id,))
db_connection.commit() db_connection.commit()
except Error as e: except Error as e:
return {"Failed": f"Failed to delete user. {e}"}, 500 return {"Failed": f"Failed to delete user. {e}"}, 500
@ -138,11 +154,12 @@ class UserService:
:rtype: Tuple[Union[dict, str], int] :rtype: Tuple[Union[dict, str], int]
""" """
try:
if not UserService.__verify_email(new_email): if not UserService.__verify_email(new_email):
return {"Failed": "Failed to verify email. Try another email"}, 400 return {"Failed": "Failed to verify email. Try another email"}, 400
try: with db_connection.cursor() as cursor:
db_cursor.execute("update user set email = %s where id = %s", (new_email, user_id)) cursor.execute("update user set email = %s where id = %s", (new_email, user_id))
db_connection.commit() db_connection.commit()
except Error as e: except Error as e:
return {"Failed": f"Failed to update email. Email is likely in use already. Error: {e}"}, 500 return {"Failed": f"Failed to update email. Email is likely in use already. Error: {e}"}, 500
@ -162,11 +179,12 @@ class UserService:
:rtype: Tuple[Union[dict, str], int] :rtype: Tuple[Union[dict, str], int]
""" """
try:
if not UserService.__verify_name(new_username): if not UserService.__verify_name(new_username):
return {"Failed": "Failed to verify username. Try another one"}, 400 return {"Failed": "Failed to verify username. Try another one"}, 400
try: with db_connection.cursor() as cursor:
db_cursor.execute("update user set username = %s where id = %s", (new_username, user_id)) cursor.execute("update user set username = %s where id = %s", (new_username, user_id))
db_connection.commit() db_connection.commit()
except Error as e: except Error as e:
return {"Failed": f"Failed to update username. Username is likely in use already. Error: {e}"}, 500 return {"Failed": f"Failed to update username. Username is likely in use already. Error: {e}"}, 500
@ -186,13 +204,14 @@ class UserService:
:rtype: Tuple[Union[dict, str], int] :rtype: Tuple[Union[dict, str], int]
""" """
try:
if not UserService.__verify_password(new_password): if not UserService.__verify_password(new_password):
return {"Failed": "Failed to verify password. Try another (stronger) one"}, 400 return {"Failed": "Failed to verify password. Try another (stronger) one"}, 400
hashed_password = bcrypt.hashpw(new_password.encode('utf-8'), bcrypt.gensalt()) hashed_password = bcrypt.hashpw(new_password.encode('utf-8'), bcrypt.gensalt())
try: with db_connection.cursor() as cursor:
db_cursor.execute("update user set password = %s where id = %s", (new_username, user_id)) cursor.execute("update user set password = %s where id = %s", (new_username, user_id))
db_connection.commit() db_connection.commit()
except Error as e: except Error as e:
return {"Failed": f"Failed to update password. Error: {e}"}, 500 return {"Failed": f"Failed to update password. Error: {e}"}, 500