0
votes

I'm writing Firestore security rules for my project. I want to allow users to edit information in their own user page, but not in anyone else's. Right now I don't save userId as a field in each user, only as the reference to the user document. I know how to access fields in each user, but not the reference to them. See picture:

enter image description here


match /Users/{document} {
 allow update: if request.auth.uid == userId; //how do I reach the userId without having it as a field
}

I do not want to add userId as a field in each user, there must be an easy way of accessing the path.

2

2 Answers

1
votes

As mentioned in the Firestore docs you get the document id from the match query.

In your case this would be document from match /Users/{document}. You could also rename this query to match /Users/{userId} to make it work.

1
votes

Check the second example in the documentation on using authentication information in security rules:

Another common pattern is to make sure users can only read and write their own data:

service cloud.firestore {
  match /databases/{database}/documents {
    // Make sure the uid of the requesting user matches name of the user
    // document. The wildcard expression {userId} makes the userId variable
    // available in rules.
    match /users/{userId} {
      allow read, update, delete: if request.auth.uid == userId;
      allow create: if request.auth.uid != null;
    }
  }
}

So in your case that'd be if request.auth.uid == document.