首页 > 解决方案 > 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。当他们没有代码时,他们无法写入它。

有可能这样吗?如果是这样,我该怎么做。

标签: firebasefirebase-realtime-databasefirebase-security

解决方案


我可以想到两种方法来处理这样的事情:

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 在其键中不支持的字符:. $ # [ ] /)


推荐阅读