Firebase用户读取所有,写入新的,但只修改自己的数据
Firebase user read all, write new, but only modify his own data
我在 Firebase 上有下一个场景:
有两件事,用户和事件。
我希望 Users 能够创建新的 Events,查看所有现有事件,但只能修改他们创建的事件。
意思是UserOne创建了EventOne,可以看到EventOne和EventTwo,但是只能修改EventOne。
我的结构如下:
-events
-eventOne
endTime:
id:
name:
providerId:
startTime:
userId:
-eventTwo
endTime:
id:
name:
providerId:
startTime:
userId:
-users
-userOne
-userTwo
我当前的规则几乎是默认规则:
{
"rules": {
"users": {
"$uid": {
// grants write access to the owner of this user account whose uid must exactly match the key ($uid)
".write": "auth !== null && auth.uid === $uid",
// grants read access to any user who is logged in with an email and password
".read": "auth != null && auth.uid == $uid"
}
},
"events": {
".read": "auth != null",
".write": "auth != null"
}
}
}
提前致谢。
为确保所有用户都能看到所有事件,您可以将事件的读取规则设置为 true
或 auth != null
,如果您希望读者是至少经过身份验证。
为确保事件只能由其创建者修改,请在事件旁边记录原始作者并使用 auth.uid
进行验证。
{
"rules": {
"events": {
"$eventid": {
".read": "auth != null",
".write": "auth != null && (!data.exists() || data.child('author').val() === auth.uid) && newData.hasChild('author')",
"author": {
".write": "newData.val() === auth.uid"
}
}
}
}
}
在上面,我们使用!data.exists()
来检查此位置是否存在事件。如果不存在任何事件,任何人都可以在此位置添加一个。接下来,data.child('author').val() === auth.uid
确保如果一个事件存在,只有作者可以修改它。
我在 Firebase 上有下一个场景:
有两件事,用户和事件。
我希望 Users 能够创建新的 Events,查看所有现有事件,但只能修改他们创建的事件。
意思是UserOne创建了EventOne,可以看到EventOne和EventTwo,但是只能修改EventOne。
我的结构如下:
-events
-eventOne
endTime:
id:
name:
providerId:
startTime:
userId:
-eventTwo
endTime:
id:
name:
providerId:
startTime:
userId:
-users
-userOne
-userTwo
我当前的规则几乎是默认规则:
{
"rules": {
"users": {
"$uid": {
// grants write access to the owner of this user account whose uid must exactly match the key ($uid)
".write": "auth !== null && auth.uid === $uid",
// grants read access to any user who is logged in with an email and password
".read": "auth != null && auth.uid == $uid"
}
},
"events": {
".read": "auth != null",
".write": "auth != null"
}
}
}
提前致谢。
为确保所有用户都能看到所有事件,您可以将事件的读取规则设置为 true
或 auth != null
,如果您希望读者是至少经过身份验证。
为确保事件只能由其创建者修改,请在事件旁边记录原始作者并使用 auth.uid
进行验证。
{
"rules": {
"events": {
"$eventid": {
".read": "auth != null",
".write": "auth != null && (!data.exists() || data.child('author').val() === auth.uid) && newData.hasChild('author')",
"author": {
".write": "newData.val() === auth.uid"
}
}
}
}
}
在上面,我们使用!data.exists()
来检查此位置是否存在事件。如果不存在任何事件,任何人都可以在此位置添加一个。接下来,data.child('author').val() === auth.uid
确保如果一个事件存在,只有作者可以修改它。