如何在Django中实施基于帐户的分离 [英] How to enforce account based separation in Django
问题描述
ForeignKey(Account)
。 确保每个帐户
(每个帐户在其自己的子域中)只能访问自己的数据是最简单的方法是什么?我们有一个填充子域名的中间件,以及每个请求的当前帐户。
我们可以通过添加一个过滤器(....,account = request.account)
在我们的所有观点。这是不可取的,因为
-
filter(....,account = request.account)
将被添加到所有查询中,这使得这个非干,重复和容易出错。 - 如果有一个更大的风险丢失过滤器,任何地方都有安全风险。
我不认为有任何明确的赢家,特别是如果您认为并不是所有的查询都需要通过帐户过滤。还要考虑旧的 threadlocals
技巧被认为是不可靠的,这意味着自动插入过滤器参数的唯一方法将是中间件我猜...但似乎也不可靠,复杂对我来说,
我还没有想出一个很好的方法来让一个查询管理器可以在这里帮助,但可能是可能的。
所以,我认为多租户数据库的最佳解决方案只是为了确保所有的查询都被帐户过滤。您可以执行以下操作:
-
调试模式中间件,如中间件:记录所有权筛选器
-
在您的测试中检查任何测试生成的sql并验证帐户字段是否在查询中。您还可以在测试夹具中包含其他帐户数据,您的测试将确保不会在任何查询结果中显示。
-
确保所有查询在代码审查期间检查过滤器
当然不漂亮,但我能做到最好远。
I have a Django app which has a single-account model. We are converting this to be multi-account, so almost every model will have a ForeignKey(Account)
.
What is the easiest way to make sure that each Account
(each account is in its own subdomain) can only access its own data? We have a middleware that populates the subdomain, and the current account on each request.
We can do this the hard way, by adding a filter(...., account = request.account)
in all of our views. This is not desirable as,
filter(...., account = request.account)
will be added to all of the queries, making this non-dry, repetative and error-prone.- Bigger risk is if there is a missing filter, anywhere it is security risk.
I don't think there is any clear winner, especially if you consider that not all queries will need to be filtered by account. Also consider the old threadlocals
trick is considered unreliable which means the only way to do automatic insertion of filter parameters would be with middleware I guess... but that also seems unreliable and complex to me.
I also haven't come up with a good way to make a query manager that can help here, but it might be possible.
So, I think the best solution for a "multi-tenant" database is just to make sure all your queries are filtered by account. You can do this with:
Debug mode middleware such as Middleware: Record ownership screener
In your tests check the sql generated by any tests and verify the account field is in the query. You could also include "other account" data in your test fixtures that your test would make sure do not show up in any query results.
Making sure all queries are checked for the filter during code review
Certainly not pretty, but the best I've been able to do so far.
这篇关于如何在Django中实施基于帐户的分离的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!