【问题标题】:Firestore Rules - dynamic pathFirestore 规则 - 动态路径
【发布时间】:2018-11-25 00:21:29
【问题描述】:

我正在尝试在 Firestore 的规则中创建动态连接。

我有一个用户集合和一个角色集合,用户集合中的每个用户都有一个“字符串”字段,该字段与角色集合中相应角色的 Firebase 生成的 ID 匹配。

为了实现这一点,我尝试动态获取 ID,然后从角色中检索适当的数据。

我的代码如下:

service cloud.firestore {
match /databases/{database}/documents {
    match /{collections}/{collection=**} {
        function getRole() {
            return get(/databases/$(database)/documents/users/$(request.auth.uid)).data.role;
        }

        function getPermissions(role) {
            return get(/databases/$(database)/documents/roles/$(role)).data.test;
        }

        allow read: if true;

        // Role equals to 12345
        // allow write: if getRole() == 12345; <-- THIS WORKS
        // allow write: if getPermissions(12345) == true; <-- THIS WORKS
        // Need to put dynamic getRole() which equals to 12345 inside of getPermissions() 
        // instead of the static 12345

        // THIS DOES NOT WORK           
        allow write: if getPermissions(getRole()) == true;
    }
}}

这不起作用的一个潜在原因是 get() 函数是异步的,并且不等待前一个函数完成,因此它无法使用其数据。

任何帮助将不胜感激。接受变通办法、数据结构更改等...

【问题讨论】:

    标签: javascript firebase firebase-authentication google-cloud-firestore


    【解决方案1】:

    对您的示例进行了测试,它对我有用

    service cloud.firestore {
        match /databases/{database}/documents {
    
            function getRole() {
                return get(/databases/$(database)/documents/test-user/$(request.auth.uid)).data.role;
            }
    
            function getPermissions(role) {
                return get(/databases/$(database)/documents/test-role/$(role)).data.rights;
            }
    
            match /test-user/{userid} {
                allow read: if true; 
                allow write: if getPermissions(getRole()) == 'all';
            }
        }
    }
    

    我的测试集内容是

    /test-user/0fludECgWKg88Gn5SjNYPc3Opmx2 (id of my test user) has: 
        {"role": "tr"}
    
    /test-role/tr has: 
        {"rights": "all"}
    

    如果/test-role/tr 不存在或rights 没有值all,写请求被拒绝

    在您的情况下,可能只是函数 getPermissions 的类型是字符串,而测试需要一个布尔值。

    【讨论】:

      猜你喜欢
      • 2019-08-14
      • 2019-01-31
      • 2016-07-29
      • 1970-01-01
      • 2019-01-15
      • 2018-11-15
      • 1970-01-01
      • 2019-10-14
      • 1970-01-01
      相关资源
      最近更新 更多