获取Django-tastypie经过身份验证的用户详细信息

时间:2012-07-19 04:10:53

标签: django

我已经实现了django项目,它包括tastypie应用程序。客户端可以将请求发送到CRUD操作。

我在访问已记录的用户详细信息时遇到问题。在这里,我正在尝试实现BasicAuthentication +基于令牌的身份验证。

这是我的自定义实现

from tastypie.authentication import Authentication
from tastypie.authorization import Authorization

class MyAuthentication(Authentication):

    def is_authenticated(self, request, **kwargs):
        return True

    from django.contrib.sessions.models import Session
    if 'sessionid' in request.COOKIES:
        try:
            s = Session.objects.get(pk=request.COOKIES['sessionid'])
        except Exception,e:
            return False

        # get the user_id from the session
        if '_auth_user_id' in s.get_decoded():
            # try to find the user associated with the given sessionid
            try:
                u = User.objects.get(pk=s.get_decoded()['_auth_user_id'])
                if u is not None:
                    return False
            except Exception,e:
                return False
        else:
            return False
    else:
        return False

    def get_identifier(self, request):
        return request.user.username

那么我的资源文件,我正在尝试访问MyAuthenticate类。

class InvoiceResource(ModelResource):
    user = fields.ForeignKey(UserResource, 'user')
    class Meta:
        user = User.objects.get(pk=1)
        queryset = user.invoice_set.all()
        resource_name = 'invoice'
        authorization = Authorization()
        authentication = MyAuthentication();

这是问题出现了。我需要加载属于登录用户的所有发票。基本上我想将记录的用户ID作为此查询的参数传递。

user = User.objects.get(pk=1)

任何想法?

1 个答案:

答案 0 :(得分:0)

有关最新版本,请参阅Implementing Your Own Authorization。该烹饪书(截至2013年4月18日)已过时,并且不推荐使用apply_authorization_limits

新方案是创建自定义授权并应用它。授权可以检查您想要的任何内容。在文档中,请参阅UserObjectsOnlyAuthorization,了解您所谈论的内容。

相关问题