Rajarshi
Rajarshi

Reputation: 2509

Firestore write security rule for specific user using auth names

New to Firestore security rules and is trying to understand it. I'm trying to write a security rule that allow only admins in my collection to write data and every one to read it.

The collection of admins has document ids as admin names, that is for example, "Mary Lane". Within the documents I've fields:

email: "[email protected]"
uId: "firestore_user_Id"

The uId is the id of Firestore user id. The data to write is an object Message and is:

new Message(uId, title, messageBody, timestamp)

Currently I'm trying to match the request.auth.uid with the id of the admins that are stored within the collection:

service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read;
      allow write: if request.auth.uid == resource.data.uId;
    }
  }
}

Is this is write or am I doing something wrong. Any help is appreciated.

Upvotes: 1

Views: 1939

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 600130

Since the admin's name is not available in this rule allow write: if request.auth.uid == resource.data.uId;, there is no way to look up the document to check it they're an admin.

You'll need a collection where you keep a document for each admin with their UID as the document key/name. Once you have that, you can check for the existence of such a document in the rule with:

allow write: if exists(/databases/$(database)/documents/admins/$(request.auth.uid));

Also see the documentation on accessing other documents.

Upvotes: 7

Related Questions