From 6ba9539fcb1de38a97bc4a905282c3138ee278d2 Mon Sep 17 00:00:00 2001 From: white <122345776@umail.ucc.ie> Date: Wed, 26 Feb 2025 20:40:04 +0000 Subject: [PATCH] UPDATE: moved admin database usage to admin_utils --- web_server/blueprints/admin.py | 16 ++++---------- web_server/utils/admin_utils.py | 39 +++++++++++++++++++++++++++++++++ 2 files changed, 43 insertions(+), 12 deletions(-) diff --git a/web_server/blueprints/admin.py b/web_server/blueprints/admin.py index 9efe9c5..4830b37 100644 --- a/web_server/blueprints/admin.py +++ b/web_server/blueprints/admin.py @@ -1,6 +1,6 @@ from flask import Blueprint, session -from database.database import Database from utils.utils import sanitize +from utils.admin_utils import * admin_bp = Blueprint("admin", __name__) @@ -9,21 +9,13 @@ def admin_delete_user(banned_user): # Sanitise the user input banned_user = sanitize(banned_user) - # Create a connection to the database - db = Database() - db.create_connection() - # Check if the user is an admin username = session.get("username") - is_admin = db.fetchone(""" - SELECT is_admin - FROM users - WHERE username = ?; - """, (username,)) + is_admin = check_if_admin(username) # Check if the user exists - user_exists = db.fetchone("""SELECT user_id from users WHERE username = ?;""", (banned_user)) + user_exists = check_if_user_exists(banned_user) # If the user is an admin, try to delete the account if is_admin and user_exists: - db.execute("""DELETE FROM users WHERE username = ?;""", (banned_user)) \ No newline at end of file + ban_user(banned_user) \ No newline at end of file diff --git a/web_server/utils/admin_utils.py b/web_server/utils/admin_utils.py index e69de29..61c1d42 100644 --- a/web_server/utils/admin_utils.py +++ b/web_server/utils/admin_utils.py @@ -0,0 +1,39 @@ +from database.database import Database + +def check_if_admin(username): + # Create a connection to the database + db = Database() + db.create_connection() + + is_admin = db.fetchone(""" + SELECT is_admin + FROM users + WHERE username = ?; + """, (username,)) + + return is_admin + +def check_if_user_exists(banned_user): + # Create a connection to the database + db = Database() + db.create_connection() + + user_exists = db.fetchone(""" + SELECT user_id + FROM users + WHERE username = ?;""", + (banned_user,)) + + return user_exists + +def ban_user(banned_user): + """Ban a user.""" + # Create a connection to the database + db = Database() + db.create_connection() + + db.execute(""" + DELETE FROM users + WHERE username = ?;""", + (banned_user) + ) \ No newline at end of file