为什么基于类的视图未对用户进行身份验证?

时间:2019-11-29 21:42:52

标签: python-3.x django-rest-framework python-decorators

我正在使用rest_framework_simplejwt进行身份验证。我的user / urls.py看起来像这样:

from django.contrib import admin
from . import views as user_views
from user.security.jwt_auth import GetToken
admin.autodiscover()


# Setup the URLs and include login URLs for the browsable API.
urlpatterns = [
    path('login', GetToken.as_view(), name='login'),
]

此路由运行良好,它返回access_token和refresh_token。 现在这是我的client / urls.py

from django.urls import path, include
from django.contrib import admin
from client import views as client_views
admin.autodiscover()


urlpatterns = [
    path('client', client_views.ClientList.as_view()),
    path('client/<int:pk>', client_views.ClientDetail.as_view()),
    path('create_client', client_views.create_client)
]

在这里,我正在尝试为班级使用装饰器。装饰器工作良好,问题在于装饰器函数内部不存在request.user,而是必须执行request.request.user。当我这样做时,用户是AnonymousUser。我已经通过在Authorization标头中发送access_token在基于函数的视图上尝试了此装饰器,并且我能够获得正确的用户,换句话说,JWT Auth自动运行。那么为什么它在这种情况下不起作用?

user / security / decorators.py

def authentication_for_class(function):
    def wrap(request, *args, **kwargs):
        # todo: Finish permissions
        print(request.request.user)
        if request.request.user.is_anonymous:
            return JsonResponse({"detail": "You do not have permission to perform this action."}, status=403)
        return function(request, *args, **kwargs)

    wrap.__doc__ = function.__doc__
    wrap.__name__ = function.__name__
    return wrap

这是我的客户/view.py

from user.security.decorators import authentication_for_class


class ClientList(APIView):

    @authentication_for_class
    def dispatch(self, request, *args, **kwargs):
        return super(ClientList, self).dispatch(request, *args, **kwargs)

0 个答案:

没有答案