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

ryt*_*tis 12 django ajax tastypie

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

用户登录后,视图中包含一些从API中提取数据的JS,后者由tastypie支持.

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

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

ryt*_*tis 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)
Run Code Online (Sandbox Code Playgroud)

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

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


Uly*_*s V 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)
Run Code Online (Sandbox Code Playgroud)