简体   繁体   中英

Validate email address in key of firebase database in security rules

I have a working project with wrongly configured database security rules.

Here's my current rule -

{
  "rules": {
    "$email": {
         ".read": "$email == auth.token.email.replace('.',',')",
         ".write": "$email == auth.token.email.replace('.',',')",
       },
    "test": {
      ".read": "auth != null",
      ".write": "auth != null"
    }
  } 
}

and here's my data structure -

在此处输入图像描述

I am using an email as key and I am trying to limit users to their own email keys. So I am using an email in the security rules.

I am trying to replace '.' with ',' in my security rule as '.' is a forbidden character.

What's the correct syntax for this?

I am getting permission denied error.

Edit:- It seems like I can write data to database just fine. It's something else that's causing the problem.

Edit 2:- It's the write permission that's giving me permission denied error but writing the data into database anyways. I set write permission to true and everything was working fine. But obviously I don't want that.

I can read my own node without problems with your security rules, and get rejects when reading somebody else's node.

My code:

firebase.auth().signInWithEmailAndPassword("i@puf.io", "correcthorsebatterystaple")
.then(function() {
  ref.child("i@puf,io").once("value").then(function(snapshot) {
    console.log("Got value from my own node: "+snapshot.val());
  }).catch(function(error) {
    console.error("Error while reading my own node: "+error);
  });
  ref.child("someoneelse").once("value").then(function(snapshot) {
    console.log("Got value from other node: "+snapshot.val());
  }).catch(function(error) {
    console.error("Error while reading other node: "+error);
  });
});

My rules

"66872665": {
  "$email": {
    ".read": "$email == auth.token.email.replace('.',',')"
  }
},

And my JSON in the database:

"66872665": {
  "i@puf,io": "value"
}

Running the code gives me this output:

Got value from my own node: value

Error while reading other node: Error: permission_denied at /66872665/someoneelse: Client doesn't have permission to access the desired data.

For a working repro that you can run, see: https://jsbin.com/jomipef/edit?js,console

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