Firebase规则允许服务器写入

时间:2015-11-05 02:51:37

标签: firebase

用户注册后,我们会为username孩子下的用户创建/users

如何设置规则,以便只有服务器可以创建新用户,而其他用户无法修改用户数据。

的Javascript

<script>
  var ref = new Firebase("https://myapp.firebaseio.com");
  var usersRef = ref.child('users');

  var usernameField = $('#usernameInput');
  var emailField = $('#emailInput');
  var passField = $('#passInput');
  $('#submitBtn').click(function() {
    ref.createUser({
      email    : emailField.val(),
      password : passField.val()
    }, function(error, userData) {
      if (error) {
        console.log("Error creating user:", error);
      } else {
        console.log("Successfully created user account with uid:", userData.uid);
        usersRef.push({
            uid: userData.uid,
            username: usernameField.val()
        });
      }
    });
  });

</script>

现行规则:

{
  "rules": {
    "users": {
      ".indexOn": "username",
      "$uid": {
        ".write": true,

        // grants read access to any user who is logged in with an email and password
        ".read": "auth !== null && auth.provider === 'password'"
      }
    }
  }
}

2 个答案:

答案 0 :(得分:3)

要设置某些内容以便“只有服务器可以创建新用户”,您可以使用他们的Server SDK访问您的数据库。这样,您可以设置仅适用于从服务器访问数据库的规则。

但是,如果您希望管理员使用基于Web的UI来创建新用户,则需要编写Node.js或Java后端Web服务器(使用Server SDK)。您不能使用客户端JS SDK或Firebase托管。

只需按照文档Server Side setup部分中的说明操作即可。

然后将databaseAuthVariableOverride选项添加到initializeApp

var firebase = require("firebase");

firebase.initializeApp({
  serviceAccount: "path/to/serviceAccountCredentials.json",
  databaseURL: "https://databaseName.firebaseio.com",
  databaseAuthVariableOverride: {
    // maybe use something more descriptive and unique
    uid: "server-side-app"
  }
});

然后以下规则为(警告:未经测试)

{
  "rules": {
    "users": {
      ".indexOn": "username",

      // grants write access if the authenticated user is accessing 
      // via the Server SDK
      ".write": "auth != null && auth.uid === 'server-side-app'",

      // grants read access to any user who is logged in with an email/password
      ".read": "auth != null && auth.provider === 'password'"
    }
  }
}

答案 1 :(得分:0)

使用Firebase时,没有“仅服务器”的概念。每个用户都会编写自己的数据,因此要确保您需要使用Firebase的User Based Security

在这种情况下,规则非常简单:您希望每个用户只能写入自己的节点。您可以通过将规则修改为:

来完成此操作
{
  "rules": {
    "users": {
      ".indexOn": "username",
      "$uid": {
         // grants write access to the owner of this user account
         // whose uid must exactly match the key ($user_id)
        ".write": "auth.uid === $uid",

        // grants read access to any user who is logged in with an email and password
        ".read": "auth.uid !== null && auth.provider === 'password'"
      }
    }
  }
}

请注意,我复制了Firebase documentation on User Based Security中第一个示例中的.write规则。因此,再次阅读该页面可能是一个好主意,因为它解释的不仅仅是这个问题的答案。