firebase rule if user email exists in subcollection

Viewed 378

I am trying to retrieve a document from clans collection where the docid is the clan name but i want to ensure that only the clan the user is in is retrievable.

clans collection contains documents with clanname as the id with a subcollection of members which contains documents with the user email as doc ids.

clans (collection) => clanname (document) => members (collection) => member(document)

How do I check the clan to make sure the request.auth.token.email is a document in the members subcollection

I think i need to get member to equal request.auth.token.email but not sure where to fit that in the rule.

      firebase
    .firestore()
    .collection("clans")
    .doc(clanName)
    .get()
    .then(clan => {
      this.clan = clan;
    });


  match /clans/{clanName} {
        allow create;
      allow read: if exists(/databases/clans/documents/{clanName}/members/{member});
    }

the members subcollection would contain multiple documents with the user email as the documentIds.

1 Answers

You will need to build the correct path to the document using the syntax described in the documentation (which I do suggest reading thoroughly). I suggest using the user's UID, as that is the best way to uniquely identify an account:

allow read: if exists(/databases/$(database)/documents/clans/{clanName}/members/$(request.auth.uid))

If you must use email, which I strongly suggest avoid for these sort of security rules, as you could run into problems later:

allow read: if exists(/databases/$(database)/documents/clans/{clanName}/members/$(request.auth.token.email))
Related