Home > Net >  Firebase security rules: allow 'get' when document has a specific field
Firebase security rules: allow 'get' when document has a specific field

Time:03-17

My user signup process looks like

  1. buy a license on Stripe
  2. complete account afterwards

In the Stripe webhook/cloud function, we get information on the email and the license and we store this in a new document in the firestore stripe-customers collection (with a generated id).

When completing the account afterwards, we ask email/password, authenticate with firebase and we create a document in the firestore customers collection (with id=uid)

In order to check whether a user has a valid license I want to give an authenticated user 'read' access to the stripe-customer with the matching email address. So I want to somehow check that customer/uid/email (or auth.token.email) == stripe-customer/id/email

I tried the following security rules but apparently, for 'read', request does not have a resource property.

How can I test against the value of a property in a document?

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /customers/{uid} {
      allow read, write: if request.auth != null && request.auth.uid == uid;
    }
    match /stripe-customers/{id} {
      allow read: if request.resource.data.email == request.auth.token.email;
    }
  }
}

And some related questions:

  • are there benefits in using uid as document-id versus having a generated id and a document uid property?

CodePudding user response:

The request.resource variable contains the future state of the document when updating/creating a document. Instead use resource.data that is a map of all of the fields and values stored in the document.

match /stripe-customers/{id} {
  allow read: if resource.data.email == request.auth.token.email;
}

You can read more about this in the documentation.


Are there benefits in using uid as document-id versus having a generated id and a document uid property?

Depends on use case, here I would prefer user's auth UID as document ID in customers collection and customer ID from Stripe as doc ID in stripe-customers collection. There isn't any advantage, but it just easier to get user's document from Firestore .doc('customers' uid) instead of using a where('userId', '==', uid) queries.

  • Related