我正在设计一个django-tastypie应用程序。
我有一些用户可以发表评论。但就目前而言,每个人都可以删除所有内容。
我该如何解决这个问题?
答案 0 :(得分:3)
好的,我稍微挖了一下并得到答案 您需要实现自定义Authorization对象并在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
}
答案 1 :(得分:0)
我认为您可以覆盖obj_delete
,编写自己的方法来检查对象是否属于该用户
def obj_delete(self, request=None, **kwargs):
# check that request.user owns object
# go on with the delete