简体   繁体   中英

Firebase Database Security rules - set access based on dynamic CustomClaim name

So i've managed to assign each user a custom claim based on the group they belong to using Node.js code below:

exports.giveToken = functions.database.ref("userSearch/{Id}").onCreate((snapshot,context)=>{
 if(snapshot.child("cId").exists()){
   const group = snapshot.child("cId").val();
   const userId = context.params.Id;
    return admin.auth().setCustomUserClaims(userId, {[group]: true});
 }else{
   return null;
 }

})

As you can see the companyId / customClaim name is set dynamically ie it could be 1234 or it could be 123456

Within Firebase's Database Security rules this is my rules:

{
  "rules": {
        "c" :{
        "$comp_id" : {
              "$uid": {
              ".read" :"auth.uid == $uid && auth.token.$comp_id === true",
              ".write": "auth.uid == $uid"
              }
        }
     
      }
}}

Question is two fold really, is this type of access control possible with Firebase Custom Claims and if so how do I implement it?

My end goal here is that a user Joins > is assigned a custom claim based on their group > is only able to access data from that group (or node).

Many thanks in advance.

You'll want to use square bracket notation:

{
  "rules": {
        "c" :{
        "$comp_id" : {
              "$uid": {
              ".read" :"auth.uid == $uid && auth.token[$comp_id] === true",
              ".write": "auth.uid == $uid"
              }
        }
     
      }
}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM