2014-09-18 118 views
0

我有一个快速的问题。对于我API.py文件我有以下代码:Django-Tastypie:认证和授权

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'] 

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

回答

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)