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.
39 lines
1.3 KiB
39 lines
1.3 KiB
6 months ago
|
from functools import wraps
|
||
|
from flask import request, jsonify
|
||
|
from sqlalchemy import select
|
||
|
from ..db.model import User, Session, db
|
||
|
|
||
|
def requires_role(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
|
||
|
|
||
|
session = db.session.execute(
|
||
|
|
||
|
)
|
||
|
if not session:
|
||
|
return jsonify({'error': 'Invalid or expired session'}), 401
|
||
|
user = User.query.get(session.userID)
|
||
|
if not user:
|
||
|
return jsonify({'error': 'User not found'}), 401
|
||
|
|
||
|
# If no roles specified, allow access
|
||
|
if not roles:
|
||
|
return f(*args, **kwargs)
|
||
|
|
||
|
# Check if user has any of the required roles
|
||
|
if user.role in roles:
|
||
|
return f(*args, **kwargs)
|
||
|
|
||
|
return jsonify({'error': 'Insufficient permissions'}), 403
|
||
|
|
||
|
return decorated_function
|
||
|
|
||
|
return decorator
|