import config from auth.atlas.auth_service import AtlasUMAuthService from auth.auth0.auth_service import Auth0AuthService from auth.atlas.m2m_auth_service import AtlasM2MAuthService from functools import wraps from auth.auth_helpers import get_auth_token from auth.models import AuthStrategy from utils.exceptions import Forbidden from auth.rbac import has_permissions def auth_required(f): """Authorization decorator for views. Args: f (function): View function. Returns: function: Decorated view function. Raises: Unauthorized: If authorization token is invalid or missing. """ def get_auth_strategy(token: str): auth_strategy = AuthStrategy(config.AUTH_STRATEGY) or AuthStrategy.ATLAS if auth_strategy == AuthStrategy.ATLAS: return AtlasUMAuthService(token=token) else: return Auth0AuthService(token=token) @wraps(f) def decorated(*args, **kwargs): token = get_auth_token() auth_service = get_auth_strategy(token) auth_service.authorize() return f(*args, **kwargs) return decorated def m2m_auth_required(f): @wraps(f) def decorated(*args, **kwargs): token = get_auth_token() auth_service = AtlasM2MAuthService(token) auth_service.authorize() return f(*args, **kwargs) return decorated def can(*permissions: str): """Access Control decorator This decorator checks permission of the current user. Args: *permissions (str): Required permissions Returns: function: Decorated view function. Raises: Unauthorized: If user is not authorized Forbidden: If user don't have all required permissions """ def decorator(f): @wraps(f) def decorated_function(*args, **kwargs): if has_permissions(list(permissions)): return f(*args, **kwargs) raise Forbidden() return decorated_function return decorator def composed(*decs): def deco(f): for dec in reversed(decs): f = dec(f) return f return deco