Search code examples
firebasegoogle-cloud-firestorefirebase-security

Firestore Rules for a user to create and edit his data only


I am new to firebase and and I finished building a react.js sire where the user fills a form which is saved under a sub collection called drivers, then the document of the user in users sub collection gets edited to show that he already filled the form before. now I want to make a rule so that the user can only create forms and update his own form if needed in the future, and read his own form only

my firebase structure looks like this

users:
    autoId{
        uid,
        id,
        filledForm,
    }

drivers:
    id{
       idNumber,
    }

now the id and idNumber fields in users and drivers are the same value, and the id which is the name of the doc in drivers is also the same id , now I am trying to make a firebase rule where only the user with the same id could create abd edit his data in both drivers and users how can I achieve this? here is what I have reached

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /drivers/{driver} {
      allow read,create,update: if isLoggedIn() && request.resource.data.idNumber == request.auth.token.id;

    }
    match /users/{user} {
      allow read,create,update: if isLoggedIn() && request.resource.data.id == request.auth.token.id;

    }
  }
  
    function  isLoggedIn(){
    return request.auth != null;
  }
  
  
}

Solution

  • In your path users/{user}, {user}, is actually the document Id. If you have set the authentication token ID as the users document ID you can use that to check against the request auth token id.