Django-Tastypie:身份验证和授权

时间:2014-09-18 23:30:23

标签: django authorization tastypie django-authentication

我有一个简单的问题。对于我的API.py文件,我有以下代码:

class MyAuthentication(BasicAuthentication):
def is_authenticated(self, request, **kwargs):
    if request.method == 'GET':     
        return True
    else:
        #group_name = request.body('group')
        #if Group.objects.filter(name = group_name):
        #   return super(MyAuthentication, self).is_authenticated(request, **kwargs)
        return super(MyAuthentication, self).is_authenticated(request, **kwargs) 

class MyAuthorization(DjangoAuthorization): #checks permissions
def is_authorized(self, request, object=None):
    if request.method == 'GET':
        return True
    return super(MyAuthorization, self).is_authorized(request, object)

class Sys_teamResource(ModelResource):
class Meta:
    queryset = Sys_team.objects.all()
    resource_name = 'sys_team'
    filtering = { 'sys_team' : ALL }
    authentication = MyAuthentication()
    authorization = MyAuthorization()
    validation = FormValidation(form_class=Sys_team_Form)
    allowed_methods = ['get','post','put']

此代码工作正常,但我很好奇当我用return super(MyAuthorization, self).is_authorized(request, object)替换return False时会发生什么。从概念上讲,这应该拒绝经过身份验证的用户的所有权限,并拒绝POSTING到数据库。但是,用户仍然可以。我想知道为什么会这样?此外,关于上面注释掉的代码,我只是在他属于某个组时才尝试对用户进行身份验证。但是,当我尝试request.body('group')时,我得到错误str对象不可调用。任何帮助是极大的赞赏!谢谢。

1 个答案:

答案 0 :(得分:0)

评论代码和str对象的答案不可调用:

request.data包含通常在json中的字符串中的传入帖子数据。由于request.data是字符串,所以抱怨 str对象不可调用

group_name = request.body('group')

因此,您可以使用json.loads将传入的json转换为python字典,并且可以访问传入的数据。所以你可以得到如下内容:

class MyAuthentication(BasicAuthentication):
    def is_authenticated(self, request, **kwargs):
        if request.method == 'GET':     
        return True
    else:
        import json

        group_name = json.loads(request.body)['group']

        if Group.objects.filter(name = group_name):
            return super(MyAuthentication, self).is_authenticated(request, **kwargs)

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