Firebase Firestore, send custom id to validate access by rules

Viewed 98

My application looks like this. You have an owner of a list, the owner can create and send an invite link to his friends. These friends will have to fill in a screen name and then a list_contributor document is made containing among other things a UID, the list_id. Now they will be able to contribute to the list.

The idea for the rules (in /list) is that everybody can create, the owner can delete and in order to write or update you must be either the owner or a contributor of that list. In order to make this happen the uid of the list_contributor (not auth.) will need to be sent with the request, then in the rules it will need to be checked wether a contributor document exists with the corresponding uid and if the list_id matches the id of the list you're querying to.

I don't know if all of this is even possible, however I really do not want the invitees to have to log in.

My rules look like this right now, 'allow update, write' at 'match /lists' is where it needs to happen.

service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write
      :if isSignedIn();
    }
    match /users/{userId} {
    allow create
    allow update, delete, write: if isOwner(userId);
  }
  
    match /lists {
    allow create
    allow delete: if isOwner(resource.data.ownerId)
    allow update, write
    }
  }
  
  
  //functions
  
  function isOwner(id){
        return request.auth.uid == id
  }
  
  function isSignedIn(){
    return request.auth != null
  }
}

I don't know how to make this happen, so if anyone would be able to help me it would be cool.

1 Answers

The only information passed along from a request to the security rules is:

  • The authentication token for the user in request.auth.
  • The path of the data the user is trying to access.
  • Any query parameters that are passed along in request.resource.
  • In the case of write requests, any updated value (which are then merged with any existing value) in `request.resource).

There is no way to send arbitrary custom information with your request to the Firebase security rules outside of this. So if you want to send along a list_contributor, you will have to put it into one of these .

The most common ways to do that, are:

  • Put the list_contributor as a custom claim in the user's auth token.
  • Make the list_contributor part of the path of the data the user accesses.

You might also be able to make the list_contributor part of the query that is executed to access the data, but I've never done that myself yet so am not certain.

Related