【问题标题】:Firebase security rules data.exists() not workingFirebase 安全规则 data.exists() 不起作用
【发布时间】:2018-11-05 09:51:48
【问题描述】:

here 之后,我创建了一个简单的安全规则和云函数,调用它来查看用户名是否已经存在。问题是安全规则写入检查总是通过并且只是在该位置(/username_lookup/user1)设置新值。

当我尝试使用实时数据库规则模拟器在此位置写入时,它按预期工作,即写入被阻止。

有人能发现问题吗?

firebase 安全规则

"rules": {    
 "username_lookup": {
  "$username": {
     // not readable, cannot get a list of usernames!
     // can only write if this username is not already in the db
     ".write": "!data.exists()",

     // can only write my own uid into this index
     ".validate": "newData.val() === auth.uid"
  }
 }
}

还有云功能

var fb = admin.database().ref();
createUser(uid, username);

function createUser(userId, usrname) {
    fb.child('username_lookup').child(usrname).set(userId, function(unerr) {
        if(unerr) { 
            res.setHeader('Content-Type', 'application/json');
            res.send(JSON.stringify({error: "the_error_code" }));
         }
     }); 
 }

username_lookup 对象/索引的屏幕截图

【问题讨论】:

    标签: javascript firebase firebase-realtime-database firebase-security


    【解决方案1】:

    您的 Cloud Functions 通过以下方式访问 Firebase 数据库:

    var fb = admin.database().ref();
    

    如您所见,模块为 admin,表示您正在使用 Firebase Admin SDK。 Firebase Admin SDK 的关键特性之一是:

    以完全管理员权限读写实时数据库数据。

    来源:https://firebase.google.com/docs/admin/setup

    所以 Admin SDK 实际上绕过了您的安全规则。

    将错误处理程序用于基本流控制也是一种非常糟糕的做法。

    改为使用 Firebase 事务以原子方式读取/写入具有名称的位置:

    fb.child('username_lookup').child(usrname).transaction(function(value) {
        if (value) {
            res.setHeader('Content-Type', 'application/json');
            res.send(JSON.stringify({error: "the_error_code" }));
            return; // abort the transaction
        }
        else {
            return userId;
        }
    }); 
    

    【讨论】:

    • 一如既往,感谢您的回答!我无法找到有关如何获取非管理员数据库参考的文档。我读了这篇文章stackoverflow.com/questions/44615920/…(仅供参考,答案中的链接是 404)但是这是基于触发器并使用事件对象。在我的云功能中,我正在使用发布请求。我是否需要导入另一个 Firebase SDK 才能获得非管理员参考?
    猜你喜欢
    • 2018-01-30
    • 1970-01-01
    • 2020-08-24
    • 1970-01-01
    • 2021-12-24
    • 2016-06-03
    • 2017-08-02
    • 1970-01-01
    相关资源
    最近更新 更多