基于授权的Django-tastyperest查询过滤

2024-09-30 04:31:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我希望对通过tastype提供REST接口的django web应用进行更改。应用程序:
https://github.com/OWASP/django-DefectDojo/

在应用程序中,用户拥有他们有权查看的产品,以及属于产品的端点。在

模型定义如下:
https://github.com/OWASP/django-DefectDojo/blob/master/dojo/models.py#L177https://github.com/OWASP/django-DefectDojo/blob/master/dojo/models.py#L417

我已将EndpointResource添加到dojo/api.py

class EndpointResource(BaseModelResource):
    class Meta:
        queryset = Endpoint.objects.all()
        resource_name = 'endpoints'
        fields = ['product', 'protocol', 'host', 'path', 'query', 'fragment']

        list_allowed_methods = ['get']
        detail_allowed_methods = ['get']
        include_resource_uri = True
        filtering = {
            'product': ALL,
            'protocol': ALL,
            'host': ALL,
        }
        authorization = DjangoAuthorization()
        authentication = DojoApiKeyAuthentication()
        serializer = Serializer(formats=['json'])

类产品包含:
authorized_users = models.ManyToManyField(User, blank=True)
类终结点包含:
product = models.ForeignKey(Product, null=True, blank=True, )

目前,用户可以对/api/v1/endpoints/进行身份验证,他们将看到所有端点。在

^{pr2}$

然而,理想的行为是,用户应该只能访问他们被授权使用的产品,以及这些产品的相关实体。在

在python会话中,我可以执行以下操作:

>>> from dojo.models import User, Product, Endpoint
>>> User.objects.get(username='sue').product_set.all().get().endpoint_set.all()
[<Endpoint: goliath.sue.local>, <Endpoint: goliath.suelimited.co>, <Endpoint: 192.168.10.11>]

这些与“sue”相关联的对象就是我希望API返回的对象。
什么是最好的方法来让它与tastypie一起进行?
任何帮助非常感谢,让我知道如果我需要张贴进一步的信息。在


Tags: django用户pyhttpsgithubcomtrueget
2条回答

使用链接处的代码 https://github.com/OWASP/django-DefectDojo/blob/master/dojo/finding/views.py#L68 作为指南,以下方法已添加到类EndpointResource:

def get_object_list(self, request):
    return super(EndpointResource, self).get_object_list(request).filter(product__authorized_users__in=[request.user])

它的表现就像我所描述的,但有兴趣得到反馈,看看它是否是正确的实践。

最简单的方法可能是子类DjangoAuthorization。请参见文档here。在

from tastypie.authorization import DjangoAuthorization

from tastypie.exceptions import Unauthorized


class UserEndpointAuthorization(DjangoAuthorization):

    def read_list(self, object_list, bundle):
        # Do your filter here against the queryset to limit it
        # to only the endpoints they can see.
        return object_list.filter(....)

相关问题 更多 >

    热门问题