request.user即使在Angularjs,django-tastypie登录后也是匿名的

时间:2014-09-26 06:30:29

标签: django angularjs tastypie

我在Tastypie和Django登录时遇到大麻烦。

通过AngularJSs,我发送如下登录请求:

var request = $http({
                    method: "post",
                    url: API_URL + "api/v1/global/login/",
                    data: {'user':$scope.login_user, 'password':$scope.password}


                });

然后在api.py中的LoginResource里面我添加了单独的函数(我的项目中不同类型的用户):

def login(self, request, **kwargs):
        self.method_check(request, allowed=['post'])
        data = self.deserialize(request, request.body, format=request.META.get('CONTENT_TYPE', 'application/json'))
        user = data.get('user', '')
        password = data.get('password', '')
        user = authenticate(username=user, password=password)
        if user.is_active:
           login(request, user)
           print(request.user.is_authenticated(), request.user.id, request.session.session_key)

                return self.create_response(request, {
                    'success': True,
                })

request.user.is_authenticated()显示 True 值。

我的api.py中有MessageResource:

class MessagesResource(ModelResource):
    login_user = fields.ForeignKey(UserResource, 'login_user', null=True, full=True)
    from_person = fields.ForeignKey(UserResource, 'from_person', null=True, full=True)
    to_person = fields.ForeignKey(UserResource, 'to_person', null=True, full=True)
    create_user = fields.ForeignKey(UserResource, 'create_user', null=True, full=True)
    update_user = fields.ForeignKey(UserResource, 'update_user', null=True, full=True)
    class Meta:
        allowed_methods = ['get','post','delete','put','patch']
        queryset = Messages.objects.all()
        resource_name = 'messages'
        authorization = Authorization()
        authentication = Authentication()
        always_return_data = True
        filtering = { 
            'from_person':ALL,
            'to_person':ALL_WITH_RELATIONS,
            'status':ALL
                    }

    def get_object_list(self, request):
        print('request.user.id=',request.user.id)
        return super(MessagesResource, self).get_object_list(request).filter(to_person__id=request.user.id)

此处get_object_list request.user.id内的。我究竟做错了什么?

注意:在登录控制台登录后,我重定向到' Dashboard.html' ..此重定向是否会对此请求产生任何影响?

编辑:这是我的登录资源

class GlobalLoginResource(ModelResource):
    class Meta:
        queryset = User.objects.all()
        allowed_methods = ['get','post']
        resource_name = 'global'
        authorization = DjangoAuthorization()
        excludes = ['password']

1 个答案:

答案 0 :(得分:1)

如果您使用标准Authentication,这意味着"根本没有身份验证",方法is_authenticated不会检查或分配用户请求。因此,用户bundle.request.user将在此特定资源中匿名。我看到您已在登录资源中签署了请求。所以猜测你必须在登录时使用SessionAuthenctication或生成api_key。并在MessageResource中将其用作ApiKeyAuthentication或其他。

您应该看到is_authenticated如何适用于每种身份验证方法: Authentication BasicAuthentication ApiKeyAuthentication SessionAuthentication

注意回复:此处与重定向无关。