如何检查已经从tastypie验证的用户?

时间:2011-09-09 14:47:32

标签: ajax django tastypie

当用户在Django中进行身份验证时,如何从tastypie中检查?

一旦用户登录,该视图就会包含一些从API中提取数据的JS,这是由tastypie支持的。

我在我的资源上设置了基本身份验证/ djangoauthorisation,因此浏览器会弹出http auth窗口。有什么方法可以避免这种情况吗?

到目前为止,我的想法是扩展BasicAuthentication以便它首先检查会话数据,当它找不到它时,它会回退到http auth? AFAIK AJAX调用包括会话cookie,所以这在理论上应该有效吗?有没有人做过类似的事情?

4 个答案:

答案 0 :(得分:10)

到目前为止我有这个解决方案:

class MyBasicAuthentication(BasicAuthentication):
    def __init__(self, *args, **kwargs):
        super(MyBasicAuthentication, self).__init__(*args, **kwargs)

    def is_authenticated(self, request, **kwargs):
        from django.contrib.sessions.models import Session
        if 'sessionid' in request.COOKIES:
            s = Session.objects.get(pk=request.COOKIES['sessionid'])
            if '_auth_user_id' in s.get_decoded():
                u = User.objects.get(id=s.get_decoded()['_auth_user_id'])
                request.user = u
                return True
        return super(MyBasicAuthentication, self).is_authenticated(request, **kwargs)

这似乎做我想要的。如果用户已登录,则会话包含_auth_user_id,否则,密钥将丢失。

任何人都可以想到这种方法可能导致的任何问题吗?

答案 1 :(得分:9)

您可能想在tastypie的GitHub上查看此票证:

https://github.com/toastdriven/django-tastypie/issues/197

作者提出了一种非常干净的方法来使用会话和API密钥方法验证调用。

有片段:

class ApiKeyPlusWebAuthentication(ApiKeyAuthentication):
def is_authenticated(self, request, **kwargs):
    if request.user.is_authenticated():
        return True

    return super(ApiKeyPlusWebAuthentication, self).is_authenticated(request, **kwargs)

def get_identifier(self, request):
    if request.user.is_authenticated():
        return request.user.username
    else:
        return super(ApiKeyPlusWebAuthentication, self).get_identifier(request)

答案 2 :(得分:1)

一旦用户通过您的API登录,您就拥有了Django用户会话。如果要检查用户是否仍然登录(例如,在页面刷新时)。你可以这样做:

from tastypie.resources import Resource

class LoggedInResource(Resource):
    class Meta:
        pass

    def get_list(self, request, **kwargs):

        from django.http import HttpResponse

        if request.user.is_authenticated():
            return HttpResponse(status=200)
        else:
            return HttpResponse(status=401)

客户检查:

$.ajax({
    type: "GET",
    url: '/api/loggedin/',
    success: function(data) {
        // logged in
    },
    error: function() {
        // not logged in
    }
});

答案 3 :(得分:0)

Pulegium

为什么不像以下一样简单:

class CommAuthentication(BasicAuthentication):
    def __init__(self, *args, **kwargs):
        super(CommAuthentication, self).__init__(*args, **kwargs)

    def is_authenticated(self, request, **kwargs):
        return request.user.is_authenticated()

我刚开始学习tastypie。上面的代码似乎对我有用。您的解决方案的任何优势?