Rule for Firestore that enforce user to write a document with id equals to its own uid

隐身守侯 提交于 2019-12-22 19:47:11

问题


I would like to guarantee that an user can only add a document that has the same id that its auth.uid.

For example, an user with id 1X0T6xC6hhRN5H02zLCN6SQtwby2 can only create/update the document /salesmen/1X0T6xC6hhRN5H02zLCN6SQtwby2 .

At app level, it's done by the following command (both for create and update).

 this.db
    .collection("salesmen")
    .doc(user.uid)
    .set(data)
    .then(function() { //...

At Firestore level, I am trying the following rule, but it's not working (it results in Error writing document: Error: Missing or insufficient permissions.).

match /salesmen/{salesman} {
  allow read: if true;
  allow write: if request.auth != null && resource.id == request.auth.uid;
}

How can this rule be enforced ?


回答1:


resource.id can only be used to refer to an existing document in Firestore. It doesn't work if the document being written doesn't exist yet.

Instead, you can use the salesman wildcard in your match expression to determine if the user can write a particular document, even if it doesn't exist yet:

match /salesmen/{salesman} {
  allow read: if true;
  allow write: if request.auth != null && salesman == request.auth.uid;
}

It looks like you can also use request.resource.id to reference the id of the document that possibly has not been written yet:

match /salesmen/{salesman} {
  allow read: if true;
  allow write: if request.auth != null && request.resource.id == request.auth.uid;
}

Though I can't find that explicitly discussed in the reference documentation as of this moment.



来源:https://stackoverflow.com/questions/49603701/rule-for-firestore-that-enforce-user-to-write-a-document-with-id-equals-to-its-o

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!