本文介绍了Firestore-公司内用户的安全规则的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们当前的Firestore结构如下:

Our current Firestore structure is as follows:

  • 当前我们没有使用任何子集合
  • 用户具有他们所属公司的列表
  • 每个项目仅与1家公司关联
  • 项目属于公司,当在companyId字段中写入公司UID时

我的第一个问题是如何指定该数据库定义的安全规则?有一些最佳实践方法吗?

My 1st question is how we can specify security rules defined by this database? Is there some best practice approach?

我们的第一个想法是这样做:

Our first idea was to do this:

match /databases/{database}/documents/projects/{projectUid}/{document=**} {
allow read: if 
(/databases/$(database)/documents/projects/$(projectUid)/companyId) === 
(/databases/$(database)/documents/users/$(request.auth.uid)/companyId)
}

但是,根据文档,这将意味着我们每个读取基本上需要3个读取(2个安全性查询和1个来自DB的实际读取).这似乎是对查询的浪费.

But according to the documentation this would mean that we would have for each read basically 3 reads (2 queries for security and 1 real read from DB). This seems like a waste of queries.

有没有比这更好的方法了?我们正在考虑更改为子集合:

Is there a better approach than this?We were thinking about changing to subcollections:

  • 最后,我们将在根集合"companies"和"users"中存储所有用户的详细信息
  • 项目将是公司的子集合
  • 页面将是项目的子集合
  • ...等
  • 公司将包含用户列表(而不是像现在这样)-但仅包含列表,而不包含用户详细信息

这样,我们可以使用与文档中类似的方法,其中每个匹配项都包含{companyId},在allow语句中,我们将使用类似的方法

This way we can use similar approach as from the doc, where each match would contain {companyId} and in allow statement we would use something like

match /databases/{database}/documents/companies/{companyId}/projects/{projectId} {
    allow read: if
    exists(/databases/$(database)/documents/companies/$(companyId)/users/$(request.auth.uid));
}

感谢您提供有关如何以最具扩展性,尤其是最安全的方式进行构建的建议.

Thanks for any recommendations on how to build it in the most scalable and especially most secure way.

推荐答案

您是否考虑过将用户的公司ID作为自定义声明添加到他们的个人资料中?这样一来,您的安全规则中就无需进行其他读取.

Have you considered adding a user's company ID as a custom claim to their profile? That way no additional reads are needed in your security rules.

由于设置这些声明需要Admin SDK,因此将要求您可以在某个地方运行受信任的代码.但是,如果您还没有自己的受信任环境,则可以将Cloud Functions用于基于其他操作,例如写入您当前的Firestore结构.

Since setting these claims requires the Admin SDK, it will require that you can run trusted code somewhere. But if you don't have your own trusted environment yet, you could use Cloud Functions for that e.g. based on some other action like writes to your current Firestore structure.

这篇关于Firestore-公司内用户的安全规则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 16:35