Home > OS >  How to make VIP users writable in firebase and firestore
How to make VIP users writable in firebase and firestore

Time:07-04

Firestore needs vip3 (users->uid->vip3 (Figure 1)) to write to a specific collection "post", while other collections can be written and read without vip3, My figure 1 Firestore is as shown:

enter image description here

This is the currently written rule

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {

    function isAuthenticated() {
      return request.auth.uid != null;
    }
    
    function isVipUser(rsc) {
    return rsc.data.vip == 3;
    }

    match /Users/{userId} {
    allow read: if isAuthenticated();
    allow create, update: if isAuthenticated() && isVipUser(request.resource)
    }
}
}

How to write to achieve it, the database needs VIP3 (id->uid->Profile->vip3 (Figure 2)) to write to a specific collection "post", and other collections can be written and read without VIP3, My figure 2 database is as shown:

enter image description here

This is the currently written rule

{
  "rules": {
    "some_path": {
      "$uid": {
        // Create a custom claim for each role or group
        // you want to leverage
        ".write":"data.child('ID').child(auth.uid).child('Profile').child('vip').val() === 3",
        ".read": "auth.uid != null && auth.token.reader == true"
      }
    }
  }
}

CodePudding user response:

here's how u could achieve that:

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {

    function isAuthenticated() {
      return request.auth.uid != null;
    }
    
    function isVipUser(rsc) {
    return rsc.data.vip == 3;
    }

    match /Users/{userId} {
    allow read: if isAuthenticated();
    allow create, update: if isAuthenticated() && isVipUser(request.resource)
    }

}

CodePudding user response:

This rule doesn't match your data structure:

data.child('users').child(auth.uid).child('VIP3').val() == 'Yes'

In your data structure there is a child named vip (all lowercase, no 3 in the key) with a numeric value of 3. There's also no top-level node users, but rather ID.

So the correct check would be:

data.child('ID').child(auth.uid).child('vip').val() === 3
  • Related