permissions.py 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. from rest_framework.permissions import BasePermission
  2. class ScopedPermission(BasePermission):
  3. """
  4. Check if view has scope_map and compare it with request's auth scope map
  5. Fall back to checking for user authentication
  6. """
  7. scope_map = {}
  8. def get_allowed_scopes(self, request, view):
  9. try:
  10. return self.scope_map[request.method]
  11. except KeyError:
  12. return {}
  13. def has_permission(self, request, view):
  14. if request.auth:
  15. allowed_scopes = self.get_allowed_scopes(request, view)
  16. current_scopes = request.auth.get_scopes()
  17. return any(s in allowed_scopes for s in current_scopes)
  18. return bool(request.user and request.user.is_authenticated)
  19. def get_user_scopes(self, obj, user):
  20. return set()
  21. def has_object_permission(self, request, view, obj):
  22. allowed_scopes = self.get_allowed_scopes(request, view)
  23. current_scopes = self.get_user_scopes(obj, request.user)
  24. return any(s in allowed_scopes for s in current_scopes)
  25. class UserOnlyPermission(BasePermission):
  26. """
  27. Authentication method disallows tokens. User must be logged in via session.
  28. """
  29. def has_permission(self, request, view):
  30. if request.auth:
  31. return False
  32. return bool(request.user and request.user.is_authenticated)