I am currently utilizing the Firebase database and I am in the process of configuring rules to restrict write access to users whose uid matches the userId node of the object they are attempting to write, while still allowing the creation of new objects such as new posts if they do not already exist. Therefore, new posts are permitted, and editing one's own post is also allowed, but write access is denied if the post already exists but does not belong to the user.
Something along the lines of:
"posts": {
".write": "auth !== null && posts.post.userId.val() === auth.uid
}
or possibly something like
//where posts.post represents objectRef.objectUpdating
"rules":{
".write": " auth !== null && posts.post.userId.val() === auth.uid
}
Updating the posts.postid object can be achieved as follows:
firebase.database().ref('posts').child(id).update(updates)
Here is a glimpse of how posts are structured. Threads and forums follow a similar pattern.
"posts": {
"-KsjWehQ--apjDBwSBCZ": {
"edited": {
"at": 1504037546,
"by": "ALXhxjwgY9PinwNGHpfai6OWyDu2"
},
"publishedAt": 1504035908,
"text": "some post text",
"threadId": "-KsjWehQ--apjDBwSBCY",
"userId": "ALXhxjwgY9PinwNGHpfai6OWyDu2"
},
...{post2},
...{etc}
}
I hope this explanation is clear, any assistance would be greatly appreciated.
EDIT: I have managed to implement a check when the update or create method is invoked to verify if data.userId matches the auth.uid. Updating existing data now functions properly.
However, the create method is currently not functioning, and I am uncertain of how to allow update() to create new posts or threads as before without updating if the userId does not match auth.uid.
Rules below:
{
"rules": {
".read": true,
"users": {
".indexOn": ["usernameLower", "email"],
"$user": {
".write": "auth !== null && $user === auth.uid"
}
},
"forums": {
".write": false
},
"categories": {
".write":false
},
"$resource": {
"$child": {
".write": "(auth !== null && auth.uid === data.child('userId').val()) || data.val() === null"
}
}
}
}