2017-03-07 17:17:39 -05:00
|
|
|
from django.conf import settings
|
|
|
|
|
|
|
|
from rest_framework import authentication, exceptions
|
2016-03-01 11:23:03 -05:00
|
|
|
from rest_framework.exceptions import APIException
|
2017-03-07 17:17:39 -05:00
|
|
|
from rest_framework.permissions import DjangoModelPermissions, SAFE_METHODS
|
2017-02-08 16:00:42 -05:00
|
|
|
from rest_framework.serializers import Field
|
2017-01-27 14:36:13 -05:00
|
|
|
|
2017-03-07 17:17:39 -05:00
|
|
|
from users.models import Token
|
|
|
|
|
2017-01-27 14:36:13 -05:00
|
|
|
|
|
|
|
WRITE_OPERATIONS = ['create', 'update', 'partial_update', 'delete']
|
2016-03-01 11:23:03 -05:00
|
|
|
|
|
|
|
|
|
|
|
class ServiceUnavailable(APIException):
|
|
|
|
status_code = 503
|
|
|
|
default_detail = "Service temporarily unavailable, please try again later."
|
2017-01-27 14:36:13 -05:00
|
|
|
|
|
|
|
|
2017-03-07 17:17:39 -05:00
|
|
|
class TokenAuthentication(authentication.TokenAuthentication):
|
|
|
|
"""
|
|
|
|
A custom authentication scheme which enforces Token expiration times.
|
|
|
|
"""
|
|
|
|
model = Token
|
|
|
|
|
|
|
|
def authenticate_credentials(self, key):
|
|
|
|
model = self.get_model()
|
|
|
|
try:
|
|
|
|
token = model.objects.select_related('user').get(key=key)
|
|
|
|
except model.DoesNotExist:
|
|
|
|
raise exceptions.AuthenticationFailed("Invalid token")
|
|
|
|
|
|
|
|
# Enforce the Token's expiration time, if one has been set.
|
2017-03-07 23:30:31 -05:00
|
|
|
if token.expires and not token.is_expired:
|
2017-03-07 17:17:39 -05:00
|
|
|
raise exceptions.AuthenticationFailed("Token expired")
|
|
|
|
|
|
|
|
if not token.user.is_active:
|
|
|
|
raise exceptions.AuthenticationFailed("User inactive")
|
|
|
|
|
|
|
|
return token.user, token
|
|
|
|
|
|
|
|
|
|
|
|
class TokenPermissions(DjangoModelPermissions):
|
|
|
|
"""
|
|
|
|
Custom permissions handler which extends the built-in DjangoModelPermissions to validate a Token's write ability
|
|
|
|
for unsafe requests (POST/PUT/PATCH/DELETE).
|
|
|
|
"""
|
|
|
|
def __init__(self):
|
|
|
|
# LOGIN_REQUIRED determines whether read-only access is provided to anonymous users.
|
|
|
|
self.authenticated_users_only = settings.LOGIN_REQUIRED
|
|
|
|
super(TokenPermissions, self).__init__()
|
|
|
|
|
|
|
|
def has_permission(self, request, view):
|
|
|
|
# If token authentication is in use, verify that the token allows write operations (for unsafe methods).
|
|
|
|
if request.method not in SAFE_METHODS and isinstance(request.auth, Token):
|
|
|
|
if not request.auth.write_enabled:
|
|
|
|
return False
|
|
|
|
return super(TokenPermissions, self).has_permission(request, view)
|
|
|
|
|
|
|
|
|
2017-02-08 16:00:42 -05:00
|
|
|
class ChoiceFieldSerializer(Field):
|
|
|
|
"""
|
2017-03-20 16:32:59 -04:00
|
|
|
Represent a ChoiceField as {'value': <DB value>, 'label': <string>}.
|
2017-02-08 16:00:42 -05:00
|
|
|
"""
|
|
|
|
def __init__(self, choices, **kwargs):
|
2017-03-16 16:50:18 -04:00
|
|
|
self._choices = dict()
|
|
|
|
for k, v in choices:
|
|
|
|
# Unpack grouped choices
|
|
|
|
if type(v) in [list, tuple]:
|
|
|
|
for k2, v2 in v:
|
|
|
|
self._choices[k2] = v2
|
|
|
|
else:
|
|
|
|
self._choices[k] = v
|
2017-02-08 16:00:42 -05:00
|
|
|
super(ChoiceFieldSerializer, self).__init__(**kwargs)
|
|
|
|
|
|
|
|
def to_representation(self, obj):
|
2017-03-20 16:32:59 -04:00
|
|
|
return {'value': obj, 'label': self._choices[obj]}
|
2017-02-08 16:00:42 -05:00
|
|
|
|
|
|
|
def to_internal_value(self, data):
|
2017-02-16 14:37:21 -05:00
|
|
|
return self._choices.get(data)
|
2017-02-08 16:00:42 -05:00
|
|
|
|
|
|
|
|
2017-01-27 14:36:13 -05:00
|
|
|
class WritableSerializerMixin(object):
|
|
|
|
"""
|
2017-01-31 15:35:09 -05:00
|
|
|
Allow for the use of an alternate, writable serializer class for write operations (e.g. POST, PUT).
|
2017-01-27 14:36:13 -05:00
|
|
|
"""
|
|
|
|
def get_serializer_class(self):
|
2017-01-31 15:35:09 -05:00
|
|
|
if self.action in WRITE_OPERATIONS and hasattr(self, 'write_serializer_class'):
|
|
|
|
return self.write_serializer_class
|
2017-01-27 14:36:13 -05:00
|
|
|
return self.serializer_class
|