firebase - Firebase 实时数据库写入规则
问题描述
我对 firebase 实时数据库规则有疑问。
有人创建了一个帐户,该帐户在实时数据库中创建了一个路径:
结构很简单(key、userid、其他数据)。
这是我的规则:
{
/* Visit https://firebase.google.com/docs/database/security to learn more about security rules. */
"rules": {
"waitingForApproval": {
"$uid": {
".write": true,
".read": "auth != null && $uid === auth.uid"
}
},
}
}
但现在问题来了。如何允许用户写入此对象?每个拥有代码(参见 BQUyhq)w3D)的人都可以写入对象 id。当他们没有代码时,他们无法写入它。
有可能这样吗?如果是这样,我该怎么做。
解决方案
我可以想到两种方法来处理这样的事情:
1.使用云功能:
设置写入规则false
并使用云功能进行更新。云函数将代码作为输入,验证它是否与预期代码匹配,并代表用户执行更新。例如:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
exports.updateObject = functions.https.onCall((data, context) => {
const uid = data.uid;
const code = data.code;
const codeRef = admin.database().ref(`waitingForApproval/${uid}/code`);
return codeRef.once('value').then((codeSnapshot) => {
if (codeSnapshot.val() === code) {
// Make updates on the user's behalf
}
});
});
2.在数据库中存储用户输入的代码:
添加用户可编辑部分,用户可以在其中设置代码并进行验证,例如:
用户输入代码后的数据库:
"userCodes": {
"bXUQ6PRNqvOgjwoAlm6HmYuWiYo1": {
"BQUyhq)w3D": true,
},
...
}
设置规则以检查用户是否设置了对象的代码:
"waitingForApproval": {
"$uid": {
".write": "root.child('userCodes').child($uid).child(data.child('code').val()).val() == true"
".read": "auth != null && $uid === auth.uid"
}
},
这实质上是在允许写入之前检查是否userCodes/{uid}/{code}
设置为。true
(请注意,使用此方法您的代码不能包含 firebase 在其键中不支持的字符:. $ # [ ] /)
推荐阅读
- python - 我得到 ModuleNotFoundError: No module named 'Cython' 尝试制作扩展时
- visual-studio-code - Visual Studio Code Live Share 自动完成非常延迟
- flutter - 在 Flutter 中实现通知逻辑
- python - 在 Python 3 中打印给定系列的谐波系列
- linux - 即使在步骤完成后,如何继续从 Jenkins 管道运行命令/bat 文件?
- python - 如何从 read_game 的最终位置获得棋盘?
- javascript - 将字符串转换为数字,具体取决于它们是否具有后缀,例如 1.5K
- javascript - 无法使用 VueRouter 浏览我的不同路由器链接
- python - 将 Python 列表转换为单个字符串
- javascript - 即使在相同的表单/div中,复选框也不会检查和隐藏