user3399180
user3399180

Reputation: 572

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 -

enter image description here

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.

Upvotes: 1

Views: 197

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598728

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("[email protected]", "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

Upvotes: 1

Related Questions