From 5e7f57857b91503e75437a3eebdbb8f45b8d8db0 Mon Sep 17 00:00:00 2001 From: Ivlev Denis Date: Fri, 9 Feb 2018 14:04:34 +0300 Subject: [PATCH] Add custom view for obtain token --- api/v1/auth.py | 39 +++++++++++++++++++++++++++++++++++++++ api/v1/urls.py | 4 ++-- 2 files changed, 41 insertions(+), 2 deletions(-) create mode 100644 api/v1/auth.py diff --git a/api/v1/auth.py b/api/v1/auth.py new file mode 100644 index 00000000..2bf643f4 --- /dev/null +++ b/api/v1/auth.py @@ -0,0 +1,39 @@ +from django.utils.translation import ugettext_lazy as _ + +from rest_framework import serializers +from rest_framework.authtoken.views import ObtainAuthToken +from rest_framework.compat import authenticate + + +class AuthTokenSerializer(serializers.Serializer): + email = serializers.CharField(label=_("Email")) + password = serializers.CharField( + label=_("Password"), + style={'input_type': 'password'}, + trim_whitespace=False + ) + + def validate(self, attrs): + email = attrs.get('email') + password = attrs.get('password') + + if email and password: + user = authenticate(request=self.context.get('request'), + email=email, password=password) + + # The authenticate call simply returns None for is_active=False + # users. (Assuming the default ModelBackend authentication + # backend.) + if not user: + msg = _('Unable to log in with provided credentials.') + raise serializers.ValidationError(msg, code='authorization') + else: + msg = _('Must include "username" and "password".') + raise serializers.ValidationError(msg, code='authorization') + + attrs['user'] = user + return attrs + + +class ObtainToken(ObtainAuthToken): + serializer_class = AuthTokenSerializer diff --git a/api/v1/urls.py b/api/v1/urls.py index 0118d09a..305b053d 100644 --- a/api/v1/urls.py +++ b/api/v1/urls.py @@ -2,11 +2,11 @@ from django.urls import path, include from rest_framework import permissions from rest_framework.routers import DefaultRouter -from rest_framework.authtoken import views as auth_views from drf_yasg.views import get_schema_view from drf_yasg import openapi +from .auth import ObtainToken from .views import ( CategoryViewSet, CourseViewSet, MaterialViewSet, LikeViewSet, @@ -48,6 +48,6 @@ urlpatterns = [ path('swagger(.json|.yaml)', schema_view.without_ui(cache_timeout=None), name='schema-json'), path('swagger/', schema_view.with_ui('swagger', cache_timeout=None), name='schema-swagger-ui'), path('redoc/', schema_view.with_ui('redoc', cache_timeout=None), name='schema-redoc'), - path('api-token-auth/', auth_views.obtain_auth_token), + path('api-token-auth/', ObtainToken.as_view(), name='api-token-auth'), path('', include((router.urls, 'api-root')), name='api-root'), ]