permissions.py 856 B

12345678910111213141516171819202122232425262728
  1. from functools import wraps
  2. from ninja.errors import HttpError
  3. from .authentication import AuthHttpRequest
  4. def has_permission(permissions: list[str]):
  5. """
  6. Check scoped permissions. At this time only token authentication is checked.
  7. Example: @has_permission(["event:write", "event:admin"])
  8. The decorated function requires at least one of the specified permissions.
  9. """
  10. def decorator(f):
  11. @wraps(f)
  12. async def decorated_function(request: AuthHttpRequest, *args, **kwargs):
  13. if request.auth.auth_type == "token":
  14. scopes = request.auth.data.get_scopes()
  15. if not any(s in permissions for s in scopes):
  16. raise HttpError(403, "Permission denied")
  17. return await f(request, *args, **kwargs)
  18. return decorated_function
  19. return decorator