def login(self, request, *args, **kwargs): """Авторизация. Полученный токен добавить в заголовок: HTTP_AUTHORIZATION: Token <TOKEN> Raises: AuthenticationFailed: email or password invalid """ serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = authenticate(email=serializer.data['email'], password=serializer.data['password']) if not user: raise AuthenticationFailed() user_token, created = UserToken.objects.get_or_create(user=user) if not created: user_token.refresh_token() serializer = TokenSerializer( data={ 'token': user_token.key, 'user_id': user_token.user.pk, 'first_name': user.first_name, 'last_name': user.last_name, }) serializer.is_valid(raise_exception=True) return Response(serializer.data)
def post(self, request): serializer = TokenSerializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.validated_data['user'] try: token, created = Token.objects.get_or_create(user=user) data = {'token': str(token)} return Response(data) except: return Response({ "non_field_errors": ["Username or password are not correct."] })
def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.save() if user is not None: serializer = TokenSerializer(data={ # using drf jwt utility functions to generate a token "token": jwt_encode_handler( jwt_payload_handler(user) )}) serializer.is_valid() return Response(serializer.validated_data) return Response(status=status.HTTP_401_UNAUTHORIZED)
def post(self, request): serializer = TokenSerializer(data=request.data) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data, status=status.HTTP_200_OK)