Moved login checks out to utils

This commit is contained in:
Luke Else 2024-01-22 17:35:49 +00:00
parent 897d4ab9aa
commit dc6a3b3581
2 changed files with 39 additions and 20 deletions

View File

@ -12,6 +12,7 @@ from controllers.database.user import UserController
from datetime import datetime
from utils.file_utils import allowed_file
from utils.user_utils import is_role
import os
import uuid
@ -70,16 +71,10 @@ def display_add_product():
""" Launches the page to add a new product to the site """
user_id = session.get('user_id')
# User must be logged in to view this page
if user_id is None:
flash("Please Login to view this page")
return redirect('/login')
db = UserController()
user = db.read_id(user_id)
if user is None or user.role != "Seller":
flash("You must be logged in as a Seller to view this page")
return redirect('/')
# User needs to be logged in as a seller to view this page
if not is_role("Seller"):
flash("You must be logged in as a seller to view this page!")
return redirect("/", code=302)
return render_template('index.html', content='new_product.html')
@ -91,16 +86,10 @@ def add_product():
"""
user_id = session.get('user_id')
# User must be logged in to view this page
if user_id is None:
flash("Please Login to view this page")
return redirect('/login', code=302)
db = UserController()
user = db.read_id(user_id)
if user is None or user.role != "Seller":
flash("You must be logged in as a Seller to perform this action")
return redirect('/', code=302)
# User needs to be logged in as a seller to view this page
if not is_role("Seller"):
flash("You must be logged in as a seller to view this page!")
return redirect("/", code=302)
file = request.files.get('image')
@ -127,3 +116,8 @@ def add_product():
db.create(product)
return render_template('index.html', content='new_product.html')
@blueprint.route('/ownproducts')
def display_own_products():
pass

25
utils/user_utils.py Normal file
View File

@ -0,0 +1,25 @@
from flask import session
from models.users.user import User
from controllers.database.user import UserController
def is_logged_in() -> User | None:
""" Returns the user object if the user is logged in
Otherwise returns a None type
"""
user_id = session.get('user_id')
if user_id is not None:
db = UserController()
return db.read_id(user_id)
return None
def is_role(role: str) -> bool:
""" Function that returns true if the user is logged in as"""
user = is_logged_in()
if user is not None:
return user.role == role
# User isn't logged in
return False