rest_permissions.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. from rest_framework.permissions import BasePermission, AllowAny, SAFE_METHODS
  2. from django.core.exceptions import PermissionDenied
  3. from django.utils.translation import ugettext as _
  4. from misago.core.exceptions import Banned
  5. from misago.users.bans import get_request_ip_ban
  6. from misago.users.models import Ban, BAN_IP
  7. __all__ = [
  8. 'AllowAny',
  9. 'IsAuthenticatedOrReadOnly',
  10. 'UnbannedOnly',
  11. 'UnbannedAnonOnly'
  12. ]
  13. class IsAuthenticatedOrReadOnly(BasePermission):
  14. def has_permission(self, request, view):
  15. if request.user.is_anonymous() and request.method not in SAFE_METHODS:
  16. raise PermissionDenied(
  17. _("This action is not available to guests."))
  18. else:
  19. return True
  20. class UnbannedOnly(BasePermission):
  21. def is_request_banned(self, request):
  22. ban = get_request_ip_ban(request)
  23. if ban:
  24. hydrated_ban = Ban(
  25. check_type=BAN_IP,
  26. user_message=ban['message'],
  27. expires_on=ban['expires_on'])
  28. raise Banned(hydrated_ban)
  29. def has_permission(self, request, view):
  30. self.is_request_banned(request)
  31. return True
  32. class UnbannedAnonOnly(UnbannedOnly):
  33. def has_permission(self, request, view):
  34. if request.user.is_authenticated():
  35. raise PermissionDenied(
  36. _("This action is not available to signed in users."))
  37. self.is_request_banned(request)
  38. return True