0

I am using firebase and I am getting a permission denied error when I try to write to my database. This is what I have as my rules:

{
  "rules": {
    "foo": {
      ".read": true,
      ".write": true
    }
  }
}

This is the code to write to the database:

function writeUserData(userId, name, email, imageUrl) {
  firebase.database().ref('users/' + userId).set({
    username: name,
    email: email,
    profile_picture : imageUrl
  });
} 

Why am I not able to write to my database?

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Chris
  • 7
  • 5
  • does it give any error? Please update your question with error code – Amod Gokhale Jul 02 '18 at 09:53
  • Please include the code you are using to write to the database. Without that it is not possible to answer this question with any kind of certainty. – André Kool Jul 02 '18 at 09:53
  • Possible duplicate of https://stackoverflow.com/questions/37403747/firebase-permission-denied – vahdet Jul 02 '18 at 09:55
  • function writeUserData(userId, name, email, imageUrl) { firebase.database().ref('users/' + userId).set({ username: name, email: email, profile_picture : imageUrl }); } this is the code to write to the database. the erroe says permission denied. – Chris Jul 02 '18 at 10:00
  • can you give your exact rules screenshot – MuruGan Jul 02 '18 at 10:09

1 Answers1

2

In your current rules you allow writing to the "foo" node of your database but you are trying to write to "users". Because you haven't set a rule for "users", firebase falls back on the default rule which is false.

If you want to be able to write to users you will have to change your rules to this:

{
  "rules": {
    "users": {
      ".read": true,
      ".write": true
    }
  }
}

Just remember this allows everyone (even unauthenticated users) to read/write to that location. For a more secure option you could limit it so users can only read/write their own data:

{
  "rules": {
    "users": {
      "$user_id": {
        // grants write access to the owner of this user account
        // whose uid must exactly match the key ($user_id)
        ".write": "$user_id === auth.uid",
        ".read": "$user_id === auth.uid"
      }
    }
  }
}

Example from the firebase docs.

André Kool
  • 4,880
  • 12
  • 34
  • 44
  • this is my code now: { "rules": { "users": { ".read": true, ".write": true } } } but i am still getting the error : firebase.js:1 Uncaught (in promise) Error: PERMISSION_DENIED: Permission denied – Chris Jul 02 '18 at 21:59
  • @Kato Those rules should work with the code in your question. If you still have a problem with this I suggest you update your question to include what you have tried so far. – André Kool Jul 03 '18 at 10:21