Updated user logic according to new database structure

This commit is contained in:
Thastertyn 2024-03-07 22:16:29 +01:00
parent c3ed81f706
commit b818e56954
4 changed files with 60 additions and 19 deletions

View File

@ -60,4 +60,5 @@ def get_image_name(id: int):
@bp_product.route('/create', methods=['POST']) @bp_product.route('/create', methods=['POST'])
def create_product_listing(): def create_product_listing():
return abort(501) name = request.json.get('name')

View File

@ -7,13 +7,14 @@ from app.services.user_service import UserService
@bp_user.route('/register', methods=['POST']) @bp_user.route('/register', methods=['POST'])
def register(): def register():
username = request.json.get('username') username = request.json.get('username')
displayname = request.json.get('displayname')
email = request.json.get('email') email = request.json.get('email')
password = request.json.get('password') password = request.json.get('password')
if username is None or email is None or password is None: if username is None or email is None or password is None or displayname is None:
return abort(400) return abort(400)
result, status_code = UserService.register(username, email, password) result, status_code = UserService.register(username, displayname, email, password)
return result, status_code return result, status_code
@ -43,13 +44,32 @@ def logout():
@bp_user.route('/update/username', methods=['PUT']) @bp_user.route('/update/username', methods=['PUT'])
@jwt_required() @jwt_required()
def update_username(): def update_username():
username = get_jwt_identity() user_id = get_jwt_identity()
new_username = request.json.get('new_username') new_username = request.json.get('new_username')
if new_username is None: if new_username is None:
return abort(400) return abort(400)
result, status_code = UserService.update_username(username, new_username) result, status_code = UserService.update_username(user_id, new_username)
jwt = get_jwt()
jti = jwt['jti']
exp = jwt['exp']
UserService.logout(jti, exp)
return result, status_code
@bp_user.route('/update/displayname', methods=['PUT'])
@jwt_required()
def update_displayname():
user_id = get_jwt_identity()
new_displayname = request.json.get('new_displayname')
if new_displayname is None:
return abort(400)
result, status_code = UserService.update_username(user_id, new_displayname)
jwt = get_jwt() jwt = get_jwt()

View File

@ -46,3 +46,7 @@ class ProductService:
"image_name": result['image_name'], "image_name": result['image_name'],
"image": base64.b64encode(result['image']).decode('utf-8') "image": base64.b64encode(result['image']).decode('utf-8')
} }
@staticmethod
def create_listing():
print("asd")

View File

@ -24,7 +24,7 @@ class UserService:
""" """
@staticmethod @staticmethod
def register(username: str, email: str, password: str) -> Tuple[Union[dict, str], int]: def register(username: str, displayname: str, email: str, password: str) -> Tuple[Union[dict, str], int]:
""" """
Registers a new user with the provided username, email, and password. Registers a new user with the provided username, email, and password.
@ -41,6 +41,9 @@ class UserService:
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
if not UserService.__verify_displayname(displayname):
return {"Failed": "Failed to verify display name. Try another name"}, 400
if not UserService.__verify_email(email): if not UserService.__verify_email(email):
return {"Failed": "Failed to verify email. Try another email"}, 400 return {"Failed": "Failed to verify email. Try another email"}, 400
@ -50,7 +53,7 @@ class UserService:
hashed_password = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt()) hashed_password = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt())
try: try:
db_cursor.execute("insert into user (username, email, password, role_id) values (%s, %s, %s, 1)", (username, email, hashed_password)) db_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}")
@ -71,10 +74,10 @@ class UserService:
:rtype: Tuple[Union[dict, str], int] :rtype: Tuple[Union[dict, str], int]
""" """
db_cursor.execute("select user_id, password from user where username = %s", (username,)) db_cursor.execute("select id, password from user where username = %s", (username,))
result = db_cursor.fetchone() result = db_cursor.fetchone()
user_id = result['user_id'] user_id = result['id']
password_hash = result['password'] password_hash = result['password']
if user_id is None: if user_id is None:
@ -108,7 +111,7 @@ 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]:
try: try:
db_cursor.execute("delete from user where user_id = %s", (user_id,)) db_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
@ -132,7 +135,7 @@ class UserService:
return {"Failed": "Failed to verify email. Try another email"}, 400 return {"Failed": "Failed to verify email. Try another email"}, 400
try: try:
db_cursor.execute("update user set email = %s where user_id = %s", (new_email, user_id)) db_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
@ -152,11 +155,11 @@ class UserService:
:rtype: Tuple[Union[dict, str], int] :rtype: Tuple[Union[dict, str], int]
""" """
if not UserService.__verify_username(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: try:
db_cursor.execute("update user set username = %s where user_id = %s", (new_username, user_id)) db_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
@ -182,7 +185,7 @@ class UserService:
hashed_password = bcrypt.hashpw(new_password.encode('utf-8'), bcrypt.gensalt()) hashed_password = bcrypt.hashpw(new_password.encode('utf-8'), bcrypt.gensalt())
try: try:
db_cursor.execute("update user set password = %s where user_id = %s", (new_username, user_id)) db_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
@ -218,6 +221,19 @@ class UserService:
email_regex = r"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$" email_regex = r"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$"
return re.match(email_regex, email) and len(email) <= 64 return re.match(email_regex, email) and len(email) <= 64
@staticmethod
def __verify_displayname(displayname: str) -> bool:
"""
Verifies a given display name string against a regular expression.
:param displayname: Display name string.
:type displayname: str
:return: Boolean indicating whether the display name successfully passed the check.
:rtype: bool
"""
displayname_regex = r"^[a-zA-Z.-_]{1,64}$"
return re.match(username_regex, displayname)
@staticmethod @staticmethod
def __verify_username(username: str) -> bool: def __verify_username(username: str) -> bool:
""" """
@ -228,7 +244,7 @@ class UserService:
:return: Boolean indicating whether the username successfully passed the check. :return: Boolean indicating whether the username successfully passed the check.
:rtype: bool :rtype: bool
""" """
username_regex = r"^[a-zA-Z.-_]{1,64}$" username_regex = r"^[a-z]{1,64}$"
return re.match(username_regex, username) return re.match(username_regex, username)
@staticmethod @staticmethod