Search code examples
firebase-realtime-databasefirebase-security

Secrurity rules real time database firebase 3 differents groups of users (Prenium, Access, Free )


I would like to give access data prenium only to user prenium, data access only to user access and data free to user free

I have written this security rules which make the job if we enter a specific 'user_uid'. However i would like to make the test for a list of users

{
  "rules": {
    "data_prenium": {
     ".read":"root.child('users').child('user_uid').child('status').val() === 'prenium'" ,
    },
      
    "data_free": {
     ".read":"root.child('users').child('user_uid').child('status').val() === 'free'" ,
    },

    "data_access": {
     ".read":"root.child('users').child('user_uid').child('status').val() === 'access'" ,
    },
      
     "users": {
      "$userId": {
        // grants write access to the owner of this user account
        // whose uid must exactly match the key ($user_id)
        ".read": "$userId === auth.uid",
        ".write": "$userId === auth.uid"
      }
    }
  }
}

Like that for example :

{
  "rules": {
    "data_prenium": {
     ".read":"root.child('users').children().keys().child('status').val() === 'prenium'" ,
    },
      
    "data_free": {
     ".read":"root.child('users').children().keys().child('status').val() === 'free'" ,
    },

    "data_access": {
     ".read":"root.child('users').children().keys().child('status').val() === 'access'" ,
    },
      
     "users": {
      "$userId": {
        // grants write access to the owner of this user account
        // whose uid must exactly match the key ($user_id)
        ".read": "$userId === auth.uid",
        ".write": "$userId === auth.uid"
      }
    }
  }
}

Somebody know how to do that ?


Solution

  • If you want to check the status for the user that is trying to access the data, you can use the auth.uid variable that is automatically populated when you use Firebase Authentication with the Realtime Database.

    So:

    ".read": "root.child('users').child(auth.uid).child('status').val() === 'prenium'",