Ale*_*ill 9 api django tastypie
我正在使用django-tastypie构建一个简单的API.我的想法是有两个资源:
TL; DR:我无法将Note编辑限制为Note的创建者,同时仍然允许任何用户对Note进行评论.
我使用以下设置进行身份验证:
class CreatedByEditAuthorization(Authorization):
def is_authorized(self, request, object=None, **kwargs):
return True
def apply_limits(self, request, object_list):
if request and request.method != 'GET' and hasattr(request, 'user'):
return object_list.filter(created_by=request.user)
return object_list
Run Code Online (Sandbox Code Playgroud)
简而言之,用户仅被授权编辑与created_by属性相等的对象(他们只能编辑他们创建的对象).
这连结如下:
class NoteResource(ModelResource):
comments = fields.ToManyField('myapp.api.resources.CommentResource', 'comments', null=True, blank=True)
created_by = fields.ToOneField('account.api.resources.UserResource', 'created_by')
def obj_create(self, bundle, request, **kwargs):
return super(HapResource, self).obj_create(bundle, request, created_by=request.user)
class Meta:
queryset = Note.objects.all()
allowed_methods = ['get', 'put', 'post']
authorization = CreatedByEditAuthorization()
Run Code Online (Sandbox Code Playgroud)
所以在这里,当创建一个对象时,我会自动将当前用户附加到该created_by属性并将其链接到正确的授权.
一个Comment十分简单,只是有ForeignKey一个Note资源.
问题是这样的: 如果用户A创建了一个Note而用户B试图对该Note进行评论,则tastypie发送(或模拟)一个POST请求来编辑该Note.由于用户B没有创建Note,因此该尝试被拒绝,因此创建注释失败.
问题是:有没有办法:
提前感谢任何见解.
编辑:
我有一个很大的黑客可以实现这一目标.我很确定这是安全的,但我并不积极; 我会尝试构建一些查询以确保.我没有使用fields.ForeignKeyin Comment来与之相关Note,而是创建了一个自定义字段:
class SafeForeignKey(fields.ForeignKey):
def build_related_resource(self, value, request=None, related_obj=None, related_name=None):
temp = request.method
if isinstance(value, basestring):
request.method = 'GET'
ret = super(SafeForeignKey, self).build_related_resource(value, request, related_obj, related_name)
request.method = temp
return ret
Run Code Online (Sandbox Code Playgroud)
每次我们尝试构造这个相关资源时,我们都会将请求标记为GET(因为我们希望它与SELECT查询匹配,而不是UPDATE与PUT或匹配POST).如果使用不当,这真的很难看并且可能不安全,我希望有更好的解决方案.
编辑2:从阅读tastypie源代码,据我所知,没有办法通过实际发送的查询来过滤授权.
根据https://github.com/toastdriven/django-tastypie/issues/480#issuecomment-5561036上的讨论:
Resource确定 a 是否可以更新的方法是can_update。因此,为了使其以“正确”的方式工作,您需要创建一个子类NoteResource:
class SafeNoteResource(NoteResource):
def can_update(self):
return False
class Meta:
queryset = Note.objects.all()
allowed_methods = ['get']
authorization = Authorization()
# You MUST set this to the same resource_name as NoteResource
resource_name = 'note'
Run Code Online (Sandbox Code Playgroud)
然后CommentResource以标准方式链接到注释:note = fields.ForeignKey(SafeNoteResource, 'note')。
| 归档时间: |
|
| 查看次数: |
2761 次 |
| 最近记录: |