You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
FreeBug/backend/utils/auth.py

39 lines
1.5 KiB

from functools import wraps
from flask import request, jsonify, g
6 months ago
from sqlalchemy import select, and_
from ..db.model import User, Session, db
6 months ago
from ..constants import UserRole
def requires_role(roles=None):
6 months ago
if roles is None:
roles = [UserRole.USER, UserRole.ADMIN]
6 months ago
roles = [int(r) for r in roles]
def decorator(f):
@wraps(f)
def decorated_function(*args, **kwargs):
auth_header = request.headers.get('Authorization')
if not auth_header:
return jsonify({'error': 'No authorization header sent'}), 401
try:
session_key = auth_header.split(' ')[1]
except IndexError:
return jsonify({'error': 'Invalid authorization header format'}), 401
6 months ago
session: Session = db.session.execute(
6 months ago
select(Session).where(and_(Session.key == session_key, Session.isValid == True))
6 months ago
).scalar()
if not session:
return jsonify({'error': 'Invalid or expired session'}), 401
user: User = session.user
if not user:
6 months ago
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:
return f(*args, **kwargs)
6 months ago
return jsonify({'error': 'Not authorized'}), 403
return decorated_function
return decorator