我正在设计一个 django-tastypie 应用程序。
我有一些用户可以发表评论。但是现在,每个人都可以删除所有内容。
我怎么解决这个问题 ?
好的,我对此进行了深入研究并得到了答案。
您需要实现一个自定义授权对象并在您的 ModelResource 中使用它。
下面是我正在使用的示例,它要求请求用户是超级用户或资源的所有者。
class UserPickAuthorization(Authorization):
# Checks that the records' owner is either None or the logged in user
def authorize_user(self, bundle):
print 'Authorize User'
if bundle.request.user.is_superuser:
return True
if bundle.request.user == bundle.obj.user:
return True
return False
def user(self, bundle):
print 'User'
return User.objects.get(pk=bundle.request.pk)
def read_list(self, object_list, bundle):
print 'Read List'
return object_list.filter(Q(user = self.user(bundle)) | Q(user = None))
def read_detail(self, object_list, bundle):
print 'Read Detail'
return self.authorize_user(bundle)
def create_list(self, object_list, bundle):
print 'Create List'
return object_list
def create_detail(self, object_list, bundle):
print 'Create Detail'
return self.authorize_user(bundle)
def update_list(self, object_list, bundle):
print 'Update List'
allowed = []
for obj in object_list:
print "User is superuser %s"%(bundle.request.user.is_superuser)
print "User owns obj %s"%(bundle.request.user == bundle.obj.user)
if bundle.request.user.is_superuser or bundle.request.user == bundle.obj.user:
allowed.append(obj)
return allowed
class UserPickResource(ModelResource):
pick = fields.ToOneField(TeamResource, 'pick', full=True)
user = fields.ToOneField(UserResource, 'user', full=True)
league = fields.ToOneField(LeagueResource, 'league', full=True)
class Meta:
queryset = UserPick.objects.all()
resource_name = 'userpick'
authentication = SessionAuthentication()
authorization = UserPickAuthorization()
list_allowed_methods = ['get', 'post','put', 'patch', 'delete']
always_return_data = True
filtering = {
'pick': ALL_WITH_RELATIONS,
'league': ALL_WITH_RELATIONS,
'user': ALL_WITH_RELATIONS,
'week' : ALL
}
我认为您可以重写obj_delete
,编写自己的方法来检查对象是否属于该用户
def obj_delete(self, request=None, **kwargs):
# check that request.user owns object
# go on with the delete