Firestore规则限制用户只能读/写他们的数据

时间:2019-05-10 05:54:54

标签: firebase google-cloud-firestore firebase-security firebase-security-rules

我试图将用户限制为他们自己的数据,但是当前正在共享数据。我做了一些研究(SO QuestionFirebase Docs),但他们没有为我工作。我可能已经忽略了解决方案。

数据库规则:

service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if request.auth != null;
    }

    match /users/{userId} {
      allow read, write: if request.auth.uid == userId;

      match /{document=**} {
        allow read, write: if request.auth.uid == userId;
      }
    }
  }
}

数据库数据:

users: [{
    {userId}: {
        email: "...",
        fullName: "...",
        uId: "..." // same as key
        tasks: [{
            {unique taskId}: {
                id: "...", // same as key
                desc: "...",
                priority: 3,
                completed: false
            }
        }]
    }
}]

数据查询(角度):

this.afStore
    .collection(`users`)
    .doc(`${this.authService.getUserId()}`)
    .collection(`tasks`, ref => {
            return ref
                .where('completed', '==', completed)
                .orderBy(sortField, sortOrder);
        }).snapshotChanges().pipe(
                ...
        );

这是规则问题还是数据/查询问题?我想我在规则中缺少一些细微之处...

2 个答案:

答案 0 :(得分:1)

这是您的规则:

match /{document=**} {
  allow read, write: if request.auth != null;
}

被无条件地应用于数据库中的所有文档。当规则允许访问文档时,无论正在执行什么其他规则,它都会始终授予对其的访问权限。

该规则的意思是所有用户具有对数据库中所有文档的读写访问权限。如果这不是您想要的,请完全删除规则。将其替换为仅允许仅应访问应被允许访问的用户的文档的规则。

非常清楚-您不能有一个规则,该规则允许以后再用另一条规则撤销对文档的访问。如果 any 规则允许访问,则无论其他规则怎么说,都将允许该访问。

答案 1 :(得分:0)

我遇到过类似的情况,以下是适用于我的规则集:

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /users/{userId} {
      allow read, write: if request.auth.uid == userId;
      match /{document=**} {
        allow read, write: if request.auth.uid == userId;
      }
    }
  }
}

值得注意的是,我使用了 rules_version = '2',因为它改变了 recursive wildcard

相关问题