I am creating simple crud web app, which allows designated user to create, and both login user and non-user can read the saved posts. I wonder how to structure firebase rule to achieve this?
I checked recommendation from this post: Firebase: How to structure public/private user datae, and come to my own solution as below.
I created two nodes: private (users) and public (posts), and at my redux action. I tried to write the data twice at both private and public, but get permission denied from the firebase.
My question is how to bypass this error, or if there is better approach to tackle this.
Thanks
My firebase rule:
{
"rules": {
"users": {
"$user_id": {
".read": "$user_id === 'Set_User_Id'",
".write": "$user_id === 'Set_User_Id'",
"posts": {
"$post_id": {
".validate": "newData.hasChildren(['title', 'postType', 'image', 'createdAt', 'note', 'link'])",
"title": {
".validate": "newData.isString() && newData.val().length > 0"
},
"postType": {
".validate": "newData.isString()"
},
"createdAt": {
".validate": "newData.isNumber()"
},
"image": {
".validate": "newData.isString()"
},
"link": {
".validate": "newData.isString()"
},
"note": {
".validate": "newData.isString()"
},
"$other": {
".validate": false
}
}
},
"$other": {
".validate": false
}
}
},
"posts": {
".read": true,
"$user_id": {
".write": "$user_id === 'Set_User_Id'",
}
}
}
}
Redux Action for add data twice. one at private node (users), and another at public node (posts).
export const startAddPost = (postData = {}) => {
return (dispatch, getState) => {
const uid = getState().auth.uid;
const {
title = '',
postType = '',
image = '',
createdAt = 0,
note = '',
link = ''
} = postData;
const post = { title, postType, image, createdAt, note, link }
return (
database.ref(`users/${uid}/posts`).push(post).then((ref) => {
dispatch(addPost({
id: ref.key,
...post
}))
}) &&
database.ref('posts').push(post).then((ref) => {
dispatch(addPost({
id: ref.key,
...post
}))
})
)
}
};