Firestore no permissions to execute operation

Viewed 2308

I am trying to set up rules in Firestore where everyone can read from each other's content if they are authenticated into the application but only owners of documents can create, write, update or delete them.

I have set up the following rules in Firestore:

rules_version = '2';

service cloud.firestore {
  match /databases/{database} {
    match /codes/{userID} {
      allow create, write, update, delete: if request.auth.uid == userID;
      allow read: if request.auth.uid != null;
    }
  }
}

My Firestore structure is:

Collection 'codes' > Document 'BNhBibYZ0ThCNCH2gzPRufFsIk22' > nothing in here

My request is:

firestore()
  .collection('codes')
  .doc(this.state.userID)
  .onSnapshot((querySnapshot) => {
    if (!querySnapshot) {
      let testObj = {"hello": "world"} 
      firestore().collection('codes').doc(this.state.userID).set(testObj);
    }
  });

The output I receive is: Error: [firestore/permission-denied] The caller does not have permission to execute the specified operation.

What am I doing wrong?

1 Answers

You can use the following functions I created to do this

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

function belongsTo(userId) {
    return request.auth.uid == userId;
}

You can then use it like this:

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if false;
    }

    match /codes/{userId} {
      allow read : if isUserAuthenticated();
      allow create : if belongsTo(userId);
      allow update: if belongsTo(userId);
      allow delete: if belongsTo(userId);
    }

    /* Functions */
    function isUserAuthenticated() {
      return request.auth.uid != null; 
    }

    function belongsTo(userId) {
      return request.auth.uid == userId;
    }
  }
}   

Accept as answer if it works for you. Available for more questions in the comments.

Related