限制对Django中对象的访问 [英] Limiting access to objects in Django

查看:54
本文介绍了限制对Django中对象的访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个特定的模型,该模型具有细粒度的访问设置.像这样:

I have a particular model and that model has finegrained access settings. Something like:

class Document(models.Model):
    ...
    access = models.ManyToManyField(Group)

组由特定标签组成,并且这些标签链接到用户.长话短说,文档只能由特定用户访问.重要的是,此检查不要滑过裂缝.因此,我可以看到许多选择.一种是,每次访问文档时,我都会添加支票:

Groups consist of particular tags, and those tags are linked to users. Long story short, one way or another the documents are only accessible by particular users. It is very important that this check does not slip through the cracks. So I can see a number of options. One is that every time I access a Document, I add the check:

Document.objects.filter(access__group__tag__user = request.user)

Document.objects.filter(access__group__tag__user=request.user)

但是有两个缺点:a)我在视图中查询文档模型> 100次,因此我将有很多重复的代码,并且b)很有可能有人会忘记在此添加此限制,使文档暴露在外.

But there are two drawbacks: a) I query the documents model > 100 times in my views so I will have a LOT of repeated code, and b) it's quite likely that someone will at some point forget to add this restriction in, leaving documents exposed.

因此,我认为通过自定义管理器覆盖objects()最有意义.这样,我就不会重复代码,也不会冒险忘记这样做.

So I am thinking that overwriting the objects() makes most sense, through a custom manager. That way I don't duplicate code and I don't risk forgetting to do this.

class HasAccessManager(models.Manager):
    def get_queryset(self):
        return super().get_queryset().filter(access__group__tag__user=request.user)

class Document(models.Model):
    ...
    access = models.ManyToManyField(Group)
    objects = HasAccessManager()

但是,问题出在那儿无法访问该请求:

However, the problem becomes that request is not accessible there:

未定义名称"request"

name 'request' is not defined

该如何解决?还是有更好的解决方案?

How to solve this? Or are there better solutions?

推荐答案

创建一个您的视图所继承的mixin.这样可以防止到处都有重复的代码.您将要编写单元测试,以确保适当地锁定了视图.

Create a mixin that your views inherit from. This will prevent having duplicated code everywhere. You'll want to write unit tests to make sure your views are locked down appropriately.

class HasAccessMixin(object):
    def get_queryset(self):
        qs = super().get_queryset()

        # you can still leverage a custom model manager here if you want
        # qs = qs.custom_method(access__group__tag__user=self.request.user)

        qs = queryset.filter(access__group__tag__user=self.request.user)
        return qs

class SomeListView(HasAccessMixin, ListView):
    ...

class SomeDetailView(HasAccessMixin, DetailView):
    ...

这篇关于限制对Django中对象的访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆