Search code examples
google-cloud-firestorefirebase-security

Compilation errors in firestore.rules: Unexpected 'if'


I have this compilation error in my firestore.rules:

Compilation errors in firestore.rules:
[E] 35:7 - Unexpected 'if'.
[E] 38:7 - Unexpected 'else'.
[E] 42:3 - Unexpected '}'.

The excerpt from the firestore.rules is as follows:

service cloud.firestore {
  match /databases/{database}/documents {

    match /requests/{id} {
     allow read: if isSignedIn() && ((getUserKennung() in resource.data.users_read) || userIsXY());
     allow write: if isSignedIn() && ((getUserKennung() in resource.data.users_write) || userIsXY());
    }

    function getUserKennung(){
     let email = request.auth.token.email;
     if(email.lower().matches('.*@provider[.]org')){
       return email[0:7].upper();
     }
     else {
       return 'ERR: Invalid usermail';
     }
    }

    function userIsXY(){
      return request.auth.token.email == 'XY@provider.org';
    }

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

I have no clue why the error occurs.


Solution

  • I don't think if...then...else is allowed in custom functions in security rules, so you might want to try a ternary expression like this:

    function getUserKennung(){
     let email = request.auth.token.email;
     return email.lower().matches('.*@provider[.]org')
       ? email[0:7].upper()
       : 'ERR: Invalid usermail';
    }