Tastypie请求用户在注销方法上是匿名的

时间:2013-11-22 16:47:13

标签: django api tastypie basic-authentication

使用tastypie API并为用户资源实现一些功能(遵循此示例代码:How can I login to django using tastypie),我想知道如何存放经过身份验证的用户或如何以正确的方式访问它。在测试登录方法时:

curl -u "user:pw" -H "Content-Type: application/json" -X POST --data '{"username" : "user", "password": "pw"}' http://localhost:8000/api/user/login/?format=json   
一切正常;但是logout方法将request.user视为匿名用户。如何向正确认证的用户传递注销方法?非常感谢。

来自api.py的片段

class UserResource(ModelResource):
    class Meta:
        queryset = AppUser.objects.all()
        resource_name = 'user'
        fields = ['first_name', 'last_name', 'username', 'email', 'is_staff']
        allowed_methods = ['get', 'post', 'patch']
        always_return_data = True
        authentication = BasicAuthentication()
        authorization = Authorization()

    def prepend_urls(self):
        params = (self._meta.resource_name, trailing_slash())
        return [
            url(r"^(?P<resource_name>%s)/login%s$" % params, self.wrap_view('login'), name="api_login"),
            url(r"^(?P<resource_name>%s)/logout%s$" % params, self.wrap_view('logout'), name="api_login")
        ]

    def login(self, request, **kwargs):
        """
        Authenticate a user, create a CSRF token for them, and return the user object as JSON.
        """
        self.method_check(request, allowed=['post'])

        data = self.deserialize(request, request.raw_post_data, format=request.META.get('CONTENT_TYPE', 'application/json'))

        username = data.get('username', '')
        password = data.get('password', '')

        if username == '' or password == '':
            return self.create_response(request, {
                'success': False,
                'error_message': 'Missing username or password'
            })

        user = authenticate(username=username, password=password)

        if user:
            if user.is_active:
                login(request, user)
                response = self.create_response(request, {
                    'success': True,
                    'username': user.username
                })
                response.set_cookie("csrftoken", get_new_csrf_key())
                return response
            else:
                return self.create_response(request, {
                    'success': False,
                    'reason': 'disabled',
                }, HttpForbidden )
        else:
            return self.create_response(request, {
                'success': False,
                'error_message': 'Incorrect username or password'
            })

    def logout(self, request, **kwargs):
        """ 
        Attempt to log a user out, and return success status.       
        """
        self.method_check(request, allowed=['get'])
        if request.user and request.user.is_authenticated():
            logout(request)
            return self.create_response(request, { 'success': True })
        else:
            return self.create_response(request, { 'success': False, 'error_message': 'You are not authenticated, %s' % request.user.is_authenticated() })

1 个答案:

答案 0 :(得分:5)

如果您正在制作自己的自定义tastypie网址,则需要在正确填充request.user对象之前自行调用tastypie身份验证。

def logout(self, request, **kwargs):
    """ 
    Attempt to log a user out, and return success status.       
    """
    self.method_check(request, allowed=['get'])

    # Run tastypie's BasicAuthentication
    self.is_authenticated(request)

    if request.user and request.user.is_authenticated():
        logout(request)
        return self.create_response(request, { 'success': True })
    else:
        return self.create_response(request, { 'success': False, 'error_message': 'You are not authenticated, %s' % request.user.is_authenticated() })