Firestore rule split a custom token and see if it matches

Viewed 89

I have custom claims set on users, the claims look like

organizations [
  933219123_Project-name,
  311239123_Different-Project-name
]

The first part is the DocumentId in Firestore. is it possible to split or check up until the _ via regex or something? I know we can't use loops in rules

I have a rule that works if I don't include the _Project-name part of the claim when setting them,

  match /databases/{database}/documents {
    match /organizations/{uid}/repositories/{document=**} {
      allow read: if request.auth != null && uid in request.auth.token.organizations
    }
  }

However I need both the project ID and name in my claims for the frontend stuff.

Aside from just adding both the ID and name as separate claims (seems wasteful), do I have any other options?

1 Answers

Based on the question, it's possible to use Regular Expressions on strings.

To check how to use the Regex on Firebase, you may refer to Firebase Security Rules Regular Expressions.

I would also recommend to try using matches and split for the rule to match your expectations.

For reference, I'm able to use matches. Please see below sample:

 match /databases/{database}/documents {
    match /{organizations}/{uid}/repositories/{document=**} {
      allow read: if (request.auth != null && uid in request.auth.token.organizations && organizations.matches(document+'[_]test[-]project'))
    }
  }

Note: Simulated read allowed on Firestore Rules Playground (Tested without the Auth).

Simulated read allowed without the Auth.

This will get DocumentId before the _ and ProjectId to check whether if the DocumentID with the ProjectID are in the custom claims list.

Related