Reputation: 327
I have spent the last day trying to do something on firebase rules, but I can't seem to find the solution anywhere. I am quite new to this Firebase rules thing, so please have patience :)
I have the following rules at the moment:
{
"rules": {
"users": {
"$user_id": {
// grants write access to the owner of this user account
".write": "auth != null && $user_id === auth.uid",
".read": "auth != null && $user_id === auth.uid"
}
}
}
}
That only lets users with the same id read and write their data. But, the problem is a bit more complex.
If a new user registers, there is no record of that user in the database. So I need to create a new node inside users. How can I do that? I don't know where to place the conditions so they don't interfere with each other.
A little bit of explanation would be great, I am quite lost with this kind of rules. Or if you recommend a better way to approach this, please let me know!
This is the code I'm using to create a new user:
var usersRef = firebase.database().ref('users');
usersRef.push({"hlo": "asdsd"});
But it gives me PERMISSION_DENIED.
Upvotes: 1
Views: 1598
Reputation: 11326
Your rules are perfectly fine. The problem is the code you're using to write a new user. You're creating a random key and it won't match the current user's uid. You should get the user uid from Firebase Auth:
var usersRef = firebase.database().ref('users');
var uid = firebase.auth().currentUser.uid;
usersRef.child(uid).set({"hlo": "asdsd"});
Upvotes: 1