api.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  1. from __future__ import unicode_literals
  2. from django.conf import settings
  3. from django.contrib.contenttypes.models import ContentType
  4. from rest_framework import authentication, exceptions
  5. from rest_framework.compat import is_authenticated
  6. from rest_framework.exceptions import APIException
  7. from rest_framework.pagination import LimitOffsetPagination
  8. from rest_framework.permissions import BasePermission, DjangoModelPermissions, SAFE_METHODS
  9. from rest_framework.serializers import Field, ModelSerializer, ValidationError
  10. from rest_framework.views import get_view_name as drf_get_view_name
  11. from users.models import Token
  12. WRITE_OPERATIONS = ['create', 'update', 'partial_update', 'delete']
  13. class ServiceUnavailable(APIException):
  14. status_code = 503
  15. default_detail = "Service temporarily unavailable, please try again later."
  16. #
  17. # Authentication
  18. #
  19. class TokenAuthentication(authentication.TokenAuthentication):
  20. """
  21. A custom authentication scheme which enforces Token expiration times.
  22. """
  23. model = Token
  24. def authenticate_credentials(self, key):
  25. model = self.get_model()
  26. try:
  27. token = model.objects.select_related('user').get(key=key)
  28. except model.DoesNotExist:
  29. raise exceptions.AuthenticationFailed("Invalid token")
  30. # Enforce the Token's expiration time, if one has been set.
  31. if token.is_expired:
  32. raise exceptions.AuthenticationFailed("Token expired")
  33. if not token.user.is_active:
  34. raise exceptions.AuthenticationFailed("User inactive")
  35. return token.user, token
  36. class TokenPermissions(DjangoModelPermissions):
  37. """
  38. Custom permissions handler which extends the built-in DjangoModelPermissions to validate a Token's write ability
  39. for unsafe requests (POST/PUT/PATCH/DELETE).
  40. """
  41. def __init__(self):
  42. # LOGIN_REQUIRED determines whether read-only access is provided to anonymous users.
  43. self.authenticated_users_only = settings.LOGIN_REQUIRED
  44. super(TokenPermissions, self).__init__()
  45. def has_permission(self, request, view):
  46. # If token authentication is in use, verify that the token allows write operations (for unsafe methods).
  47. if request.method not in SAFE_METHODS and isinstance(request.auth, Token):
  48. if not request.auth.write_enabled:
  49. return False
  50. return super(TokenPermissions, self).has_permission(request, view)
  51. class IsAuthenticatedOrLoginNotRequired(BasePermission):
  52. """
  53. Returns True if the user is authenticated or LOGIN_REQUIRED is False.
  54. """
  55. def has_permission(self, request, view):
  56. if not settings.LOGIN_REQUIRED:
  57. return True
  58. return request.user and is_authenticated(request.user)
  59. #
  60. # Serializers
  61. #
  62. class ValidatedModelSerializer(ModelSerializer):
  63. """
  64. Extends the built-in ModelSerializer to enforce calling clean() on the associated model during validation.
  65. """
  66. def validate(self, attrs):
  67. if self.instance is None:
  68. instance = self.Meta.model(**attrs)
  69. else:
  70. instance = self.instance
  71. for k, v in attrs.items():
  72. setattr(instance, k, v)
  73. instance.clean()
  74. return attrs
  75. class ChoiceFieldSerializer(Field):
  76. """
  77. Represent a ChoiceField as {'value': <DB value>, 'label': <string>}.
  78. """
  79. def __init__(self, choices, **kwargs):
  80. self._choices = dict()
  81. for k, v in choices:
  82. # Unpack grouped choices
  83. if type(v) in [list, tuple]:
  84. for k2, v2 in v:
  85. self._choices[k2] = v2
  86. else:
  87. self._choices[k] = v
  88. super(ChoiceFieldSerializer, self).__init__(**kwargs)
  89. def to_representation(self, obj):
  90. return {'value': obj, 'label': self._choices[obj]}
  91. def to_internal_value(self, data):
  92. return self._choices.get(data)
  93. class ContentTypeFieldSerializer(Field):
  94. """
  95. Represent a ContentType as '<app_label>.<model>'
  96. """
  97. def to_representation(self, obj):
  98. return "{}.{}".format(obj.app_label, obj.model)
  99. def to_internal_value(self, data):
  100. app_label, model = data.split('.')
  101. try:
  102. return ContentType.objects.get_by_natural_key(app_label=app_label, model=model)
  103. except ContentType.DoesNotExist:
  104. raise ValidationError("Invalid content type")
  105. #
  106. # Mixins
  107. #
  108. class WritableSerializerMixin(object):
  109. """
  110. Allow for the use of an alternate, writable serializer class for write operations (e.g. POST, PUT).
  111. """
  112. def get_serializer_class(self):
  113. if self.action in WRITE_OPERATIONS and hasattr(self, 'write_serializer_class'):
  114. return self.write_serializer_class
  115. return self.serializer_class
  116. #
  117. # Pagination
  118. #
  119. class OptionalLimitOffsetPagination(LimitOffsetPagination):
  120. """
  121. Override the stock paginator to allow setting limit=0 to disable pagination for a request. This returns all objects
  122. matching a query, but retains the same format as a paginated request. The limit can only be disabled if
  123. MAX_PAGE_SIZE has been set to 0 or None.
  124. """
  125. def paginate_queryset(self, queryset, request, view=None):
  126. try:
  127. self.count = queryset.count()
  128. except (AttributeError, TypeError):
  129. self.count = len(queryset)
  130. self.limit = self.get_limit(request)
  131. self.offset = self.get_offset(request)
  132. self.request = request
  133. if self.limit and self.count > self.limit and self.template is not None:
  134. self.display_page_controls = True
  135. if self.count == 0 or self.offset > self.count:
  136. return list()
  137. if self.limit:
  138. return list(queryset[self.offset:self.offset + self.limit])
  139. else:
  140. return list(queryset[self.offset:])
  141. def get_limit(self, request):
  142. if self.limit_query_param:
  143. try:
  144. limit = int(request.query_params[self.limit_query_param])
  145. if limit < 0:
  146. raise ValueError()
  147. # Enforce maximum page size, if defined
  148. if settings.MAX_PAGE_SIZE:
  149. if limit == 0:
  150. return settings.MAX_PAGE_SIZE
  151. else:
  152. return min(limit, settings.MAX_PAGE_SIZE)
  153. return limit
  154. except (KeyError, ValueError):
  155. pass
  156. return self.default_limit
  157. #
  158. # Miscellaneous
  159. #
  160. def get_view_name(view_cls, suffix=None):
  161. """
  162. Derive the view name from its associated model, if it has one. Fall back to DRF's built-in `get_view_name`.
  163. """
  164. if hasattr(view_cls, 'queryset'):
  165. name = view_cls.queryset.model._meta.verbose_name
  166. name = ' '.join([w[0].upper() + w[1:] for w in name.split()]) # Capitalize each word
  167. if suffix:
  168. name = "{} {}".format(name, suffix)
  169. return name
  170. return drf_get_view_name(view_cls, suffix)