2015-06-18 16:38:29 +03:00
|
|
|
from rest_framework import parsers, renderers
|
2012-11-11 04:17:50 +04:00
|
|
|
from rest_framework.authtoken.models import Token
|
|
|
|
from rest_framework.authtoken.serializers import AuthTokenSerializer
|
2018-04-05 16:07:49 +03:00
|
|
|
from rest_framework.compat import coreapi, coreschema
|
2015-06-25 23:55:51 +03:00
|
|
|
from rest_framework.response import Response
|
2017-12-17 07:11:15 +03:00
|
|
|
from rest_framework.schemas import ManualSchema
|
2020-03-03 15:27:34 +03:00
|
|
|
from rest_framework.schemas import coreapi as coreapi_schema
|
2018-02-07 22:46:17 +03:00
|
|
|
from rest_framework.views import APIView
|
2012-11-11 04:17:50 +04:00
|
|
|
|
2012-12-08 02:25:16 +04:00
|
|
|
|
2012-11-14 04:49:13 +04:00
|
|
|
class ObtainAuthToken(APIView):
|
2012-11-13 03:16:53 +04:00
|
|
|
throttle_classes = ()
|
|
|
|
permission_classes = ()
|
|
|
|
parser_classes = (parsers.FormParser, parsers.MultiPartParser, parsers.JSONParser,)
|
2012-12-08 02:25:16 +04:00
|
|
|
renderer_classes = (renderers.JSONRenderer,)
|
2015-03-22 15:35:56 +03:00
|
|
|
serializer_class = AuthTokenSerializer
|
2020-03-03 15:27:34 +03:00
|
|
|
|
|
|
|
if coreapi_schema.is_enabled():
|
2018-04-05 16:07:49 +03:00
|
|
|
schema = ManualSchema(
|
|
|
|
fields=[
|
|
|
|
coreapi.Field(
|
|
|
|
name="username",
|
|
|
|
required=True,
|
|
|
|
location='form',
|
|
|
|
schema=coreschema.String(
|
|
|
|
title="Username",
|
|
|
|
description="Valid username for authentication",
|
|
|
|
),
|
2017-12-17 07:11:15 +03:00
|
|
|
),
|
2018-04-05 16:07:49 +03:00
|
|
|
coreapi.Field(
|
|
|
|
name="password",
|
|
|
|
required=True,
|
|
|
|
location='form',
|
|
|
|
schema=coreschema.String(
|
|
|
|
title="Password",
|
|
|
|
description="Valid password for authentication",
|
|
|
|
),
|
2017-12-17 07:11:15 +03:00
|
|
|
),
|
2018-04-05 16:07:49 +03:00
|
|
|
],
|
|
|
|
encoding="application/json",
|
|
|
|
)
|
2012-11-11 04:17:50 +04:00
|
|
|
|
2020-03-03 15:27:34 +03:00
|
|
|
def get_serializer_context(self):
|
|
|
|
return {
|
|
|
|
'request': self.request,
|
|
|
|
'format': self.format_kwarg,
|
|
|
|
'view': self
|
|
|
|
}
|
|
|
|
|
|
|
|
def get_serializer(self, *args, **kwargs):
|
|
|
|
kwargs['context'] = self.get_serializer_context()
|
|
|
|
return self.serializer_class(*args, **kwargs)
|
|
|
|
|
2015-12-11 09:16:04 +03:00
|
|
|
def post(self, request, *args, **kwargs):
|
2020-03-03 15:27:34 +03:00
|
|
|
serializer = self.get_serializer(data=request.data)
|
2014-11-28 14:27:05 +03:00
|
|
|
serializer.is_valid(raise_exception=True)
|
|
|
|
user = serializer.validated_data['user']
|
|
|
|
token, created = Token.objects.get_or_create(user=user)
|
|
|
|
return Response({'token': token.key})
|
2012-11-13 03:16:53 +04:00
|
|
|
|
2012-11-14 04:49:13 +04:00
|
|
|
|
|
|
|
obtain_auth_token = ObtainAuthToken.as_view()
|