ErnieKev
ErnieKev

Reputation: 3021

Complex Firebase Security Rule

My Firebase data structure looks like

-isAdmin 
    -user1
        isAdmin: true

-users
    -user1 
        -firsName: Jane
        -lastLoggedIn: 12 March 2017
    -user2
        -firstName: John
        -lastLoggedIn: 11 March 2017

I want my admin (user 1) to be able to do the following

Add more users to -users branch. So I need the following permission (to create user3, user4...etc)

"users": {
    .write: "(auth != null) && (root.child('isAdmin').child(auth.id).val == true)
}

However I also want the non-admin user to be able to update the lastLoggedIn Entry. So I need the following permission

"users": {
    $userId: {
        "lastLoggedIn": {
            .write: "(auth != null) && ($userId == auth.id)   
        }
    }
}

Here is the problem though, firebase does not allow nested rules, since I have a .write rule under users, the .write rule under users/$userId/lastLoggedIn will be ignored I believe

Is there a way to get around this problem?

Upvotes: 2

Views: 514

Answers (1)

cartant
cartant

Reputation: 58400

It's not true that the Firebase security rules don't allow nested rules - they do. The rules cascade and the situation of which you need to be aware is that once a permission is granted it cannot be revoked by a 'nested' rule.

So the 'nested' rule will only be ignored if a rule higher up has already granted write permission. If write permission has not already been granted and the 'nested' rule grants write permission, then it is not ignored.

With these rules:

"users": {
  ".write": "(auth != null) && (root.child('isAdmin').child(auth.uid).val == true),
  "$userId": {
    "lastLoggedIn": {
      ".write": "(auth != null) && ($userId == auth.uid)
    }
  }
}

Both administrators and the users themselves will be able to write to lastLoggedIn.

Upvotes: 2

Related Questions