Reputation: 4172
I'm building an HTML/JavaScript/CSS front-end application using only Firebase as my backend (and I'd like to keep it that way, but I'm not sure if what I want to do is possible without another server).
I'm trying to implement a following/followers functionality. I have a node in the Firebase database that is basically a list of users. The object key is the user's auth uid, and the value is an object describing properties of that user object.
I want to have a "follow" button in my app that, when clicked, adds an object with the uid of the user being followed to the "following" object of the current user. Also, I want to add an object with the current user's uid to the "followers" node of the user being followed.
followers node:
following node:
The trouble I'm having is that Firebase recommends to set up their security rules something like this:
{
"rules": {
"users": {
"$uid": {
".write": "$uid === auth.uid"
}
}
}
}
This way it's fine to expose your firebase key because any given authenticated user can only write to his own object in the database. So my question is: What's the best way for me to allow one user to modify another's database object (by writing to the other user's "followers" node) while still preventing anyone with my Firebase key from maliciously writing to any/every user's object?
Upvotes: 1
Views: 481
Reputation: 342
Since firebase dataBase grantings overwrite higher level revocations, you can just leave the rule as it is and grant write permission to all users to the followers node of each user:
{
"rules": {
"users": {
"$uid": {
".write": "$uid === auth.uid"
"followers": {
".write": auth != null
}
}
}
}
You can also add a verification to the node written to followers such as !data.exists() && newData.child("uid").val() === auth.uid
to prevent users from deleting/modifying other user's followers and prevent adding random uid's as followers
Edit: Let's imagine your database structure is the folowing:
{
users: {
uid: {
(user data)
followers: {
uid : timestamp
}
}
}
}
Then the rules would be:
{
"rules": {
"users": {
"$uid": {
".write": "$uid === auth.uid",
"followers": {
"$follower": {
".write": "auth != null && !data.exists() && newData.key() === auth.uid"
}
}
That way, one user can only write new entries in the other users' followers node and that entry's key must be his uid. } }
Upvotes: 8