rest_permissions.py 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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(_("This action is not available to guests."))
  17. else:
  18. return True
  19. class UnbannedOnly(BasePermission):
  20. def is_request_banned(self, request):
  21. ban = get_request_ip_ban(request)
  22. if ban:
  23. hydrated_ban = Ban(
  24. check_type=BAN_IP,
  25. user_message=ban['message'],
  26. expires_on=ban['expires_on'])
  27. raise Banned(hydrated_ban)
  28. def has_permission(self, request, view):
  29. self.is_request_banned(request)
  30. return True
  31. class UnbannedAnonOnly(UnbannedOnly):
  32. def has_permission(self, request, view):
  33. if request.user.is_authenticated():
  34. raise PermissionDenied(
  35. _("This action is not available to signed in users."))
  36. self.is_request_banned(request)
  37. return True