permissions.py 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. from rest_framework.permissions import BasePermission
  2. from users.utils import is_user_registration_open
  3. class ScopedPermission(BasePermission):
  4. """
  5. Check if view has scope_map and compare it with request's auth scope map
  6. Fall back to checking for user authentication
  7. """
  8. scope_map = {}
  9. def get_allowed_scopes(self, request, view):
  10. try:
  11. return self.scope_map[request.method]
  12. except KeyError:
  13. return {}
  14. def has_permission(self, request, view):
  15. if request.auth:
  16. allowed_scopes = self.get_allowed_scopes(request, view)
  17. current_scopes = request.auth.get_scopes()
  18. return any(s in allowed_scopes for s in current_scopes)
  19. return bool(request.user and request.user.is_authenticated)
  20. def get_user_scopes(self, obj, user):
  21. return set()
  22. def has_object_permission(self, request, view, obj):
  23. allowed_scopes = self.get_allowed_scopes(request, view)
  24. current_scopes = self.get_user_scopes(obj, request.user)
  25. return any(s in allowed_scopes for s in current_scopes)
  26. class UserOnlyPermission(BasePermission):
  27. """
  28. Authentication method disallows tokens. User must be logged in via session.
  29. """
  30. def has_permission(self, request, view):
  31. if request.auth:
  32. return False
  33. return bool(request.user and request.user.is_authenticated)
  34. class UserRegistrationPermission(BasePermission):
  35. """
  36. If registration is closed, only first user can be created except by superuser.
  37. """
  38. def has_permission(self, request, view):
  39. return bool(
  40. is_user_registration_open() or (request.user and request.user.is_superuser)
  41. )