Выйти в Django Rest Framework - PullRequest
       32

Выйти в Django Rest Framework

3 голосов
/ 07 октября 2019

Не в состоянии реализовать пользователя logout.

Вот код. Я пытаюсь запустить из командной строки curl -d "" POST http://127.0.0.1:8001/api/v1/users/settings/logout/

Но в ответ я получаю 401 error - {"detail": "Authentication credentials were not provided."}. Хотя пользователь вошел в систему.

@action(detail=False, methods=['post'])
def logout(self, request):
    print(999)       #Nothing
    try:
        print(request.user.auth_token)
        request.user.auth_token.delete()
    except (AttributeError):
        pass
    from django.contrib.auth import logout
    logout(request)

    return Response({"success": _("Successfully logged out.")},
                    status=status.HTTP_200_OK)

Кажется, что функция даже не работает ...

from django.contrib.auth import get_user_model

from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from rest_framework import exceptions

from .utils import provide_user_to_sentry


class UserIdAuthenticateMixin:

    def authenticate_credentials(self, payload):
        """
        Returns an active user that matches the payload's user id.
        """
        User = get_user_model()
        user_id = payload.get('user_id')

        if not user_id:
            raise exceptions.AuthenticationFailed('Invalid payload.')

        try:
            user = User.objects.get(pk=user_id)
        except User.DoesNotExist:
            raise exceptions.AuthenticationFailed('Invalid signature.')

        if not user.is_active:
            raise exceptions.AuthenticationFailed('User account is disabled.')

        return user


class JSONWebTokenSentryAuthentication(UserIdAuthenticateMixin, JSONWebTokenAuthentication):
    """Wrapper around ``JSONWebTokenAuthentication``

    In case of successful authentication it reports user id and IP address to sentry for later logging

    Clients should authenticate by passing the token key in the "Authorization"
    HTTP header, prepended with the string specified in the setting
    `JWT_AUTH_HEADER_PREFIX`. For example:

        Authorization: JWT eyJhbGciOiAiSFMyNTYiLCAidHlwIj
    """
    def authenticate(self, request):
        original_response = super().authenticate(request)
        if original_response is None:
            return original_response

        user, _jwt = original_response
        provide_user_to_sentry(request, user)
        return original_response


class UserIdJSONWebTokenAuthentication(UserIdAuthenticateMixin, JSONWebTokenAuthentication):
    """Wrapper around ``JSONWebTokenAuthentication``

    Update authenticate_credentials to check user id.

    Clients should authenticate by passing the token key in the "Authorization"
    HTTP header, prepended with the string specified in the setting
    `JWT_AUTH_HEADER_PREFIX`. For example:

        Authorization: JWT eyJhbGciOiAiSFMyNTYiLCAidHlwIj
    """
    pass

1 Ответ

0 голосов
/ 07 октября 2019

Авторизация

После этого запроса я получаю токен для пользователя

curl -H "Authorization: JWT Token" -d "email=test@gmail.com&password=password" POST 'http://127.0.0.1:8001/api/v1/users/login/'

Просмотр выхода из системы

@action(detail=False, methods=['post'])
def logout(self, request):
    try:
        request.user.auth_token.delete()
    except (AttributeError, ObjectDoesNotExist):
        pass

    django_logout(request)
    return Response(status=status.HTTP_200_OK)

Запрос на выход из системы

curl -d "" -H "Authorization: JWT Token" POST 'http://127.0.0.1:8001/api/v1/users/settings/logout/'
...