首页 文章

如何为firestore规则身份验证(React-Native)传递额外的auth参数?

提问于
浏览
4

我想在我的应用程序中实现基于角色的限制 . 我在一个集合文档中有用户角色信息 . 现在我想编写规则来限制对数据库的其他集合的不同写入,更新操作 .

由于我使用带有React-Native的Firestore数据库,因此我只在插入/更新时传递相应集合的文档信息 . 那么我该如何传递用户的角色信息以便我的规则得到身份验证,并且数据不会进入其他集合 .

描述上述场景的一个示例:

/collection1/document1
{
   prop1: value1,
   prop2: value2,
   role: "WRITE"
}

/collection1/document2
{
   prop1: value1,
   prop2: value2,
   role: "READ"
}

现在考虑当前登录的用户是 document2 .

我还有另一个系列:

/collection2/doc1
{
   userRef: document1, //this is id of document1 from collection1
   ...
}

我想为collection2配置firestore规则,如果请求来自用户 role="WRITE" ,那么只允许它为isert / update文档 .

阅读了很多文章和方法,但其中任何一个都不满足这个用例 .

任何帮助,将不胜感激 .

1 回答

  • 2

    为了使规则更易于阅读,您可以创建一个获取用户角色的函数,然后在条件中使用 . 这就是 firestore.rules 文件的样子:

    service cloud.firestore {
      match /databases/{database}/documents {
        match /collection2/{doc} {
         allow read: if getUserRole() === 'READ' || getUserRole() === 'WRITE';
         allow create: if getUserRole() === 'WRITE';
         allow update: if getUserRole() === 'WRITE';
        }
        function getUserRole() {
            return get(/databases/$(database)/documents/collection1/$(request.auth.uid)).data.role;
        }
      }
    }
    

相关问题