From 0f1fc25239b1686bf1167dafff962fae4cd6eb64 Mon Sep 17 00:00:00 2001 From: Casu Al Snek Date: Sat, 11 Jan 2025 17:42:58 +0545 Subject: [PATCH 1/2] Split auth based decorators --- backend/utils/auth.py | 23 ++++++++++++++--------- 1 file changed, 14 insertions(+), 9 deletions(-) diff --git a/backend/utils/auth.py b/backend/utils/auth.py index a8bc72e..b146565 100644 --- a/backend/utils/auth.py +++ b/backend/utils/auth.py @@ -4,10 +4,7 @@ from sqlalchemy import select, and_ from ..db.model import User, Session, db from ..constants import UserRole -def requires_role(roles=None): - if roles is None: - roles = [UserRole.USER, UserRole.ADMIN] - roles = [int(r) for r in roles] +def auth_required(): def decorator(f): @wraps(f) def decorated_function(*args, **kwargs): @@ -23,16 +20,24 @@ def requires_role(roles=None): ).scalar() if not session: return jsonify({'error': 'Invalid or expired session'}), 401 - user: User = session.user if not user: return jsonify({'error': 'User not found for the Access token'}), 401 g.current_session = session g.current_user = user - # If no roles specified, allow access - if not roles: - return f(*args, **kwargs) - if user.role in roles: + g.is_authed = True + return f(*args, **kwargs) + return decorated_function + return decorator + +def requires_role(roles=None): + if roles is None: + roles = [UserRole.USER, UserRole.ADMIN] + roles = [int(r) for r in roles] + def decorator(f): + @wraps(f) + def decorated_function(*args, **kwargs): + if g.current_user.role in roles: return f(*args, **kwargs) return jsonify({'error': 'Not authorized'}), 403 return decorated_function From 2af17a17641323f27e50242f340ea3ecef507352 Mon Sep 17 00:00:00 2001 From: Casu Al Snek Date: Sat, 11 Jan 2025 18:08:39 +0545 Subject: [PATCH 2/2] Check authorization in requires role guard decorator --- backend/utils/auth.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/backend/utils/auth.py b/backend/utils/auth.py index b146565..73ba416 100644 --- a/backend/utils/auth.py +++ b/backend/utils/auth.py @@ -37,8 +37,9 @@ def requires_role(roles=None): def decorator(f): @wraps(f) def decorated_function(*args, **kwargs): + if g.get('is_authed', False) is False: + return jsonify({'error': 'Unauthorized'}) if g.current_user.role in roles: return f(*args, **kwargs) - return jsonify({'error': 'Not authorized'}), 403 return decorated_function return decorator \ No newline at end of file