繁体   English   中英

为什么我在 firebase 数据库中的规则不起作用?

[英]Why my rule in firebase database is not working?

我正在尝试添加一个规则,如果用户已经存在且具有相同的 email,则该规则会自动合并两个用户,并且只保留其中一个用户的新用户最新数据。

match /users/{userId} {
    allow create: if request.resource.data.email != null;
    allow update: if request.resource.data.email != null && request.auth.uid == userId;
    function isDuplicateEmail() {
        return get(/databases/$(database)/documents/users/$(request.resource.data.email)).exists;
    }
    function mergeUsers(userId) {
        // Get the data of the new user
        let newUser = get(/databases/$(database)/documents/users/$(userId)).data;
        
        // Get the data of the existing user
        let existingUser = get(/databases/$(database)/documents/users/$(newUser.email)).data;
        
        // Merge the data from the two users
        let mergedData = {...existingUser, ...newUser};
        
        // Update the data of the existing user
        return update(/databases/$(database)/documents/users/$(newUser.email), mergedData);
    }
    allow create: if !isDuplicateEmail()
    allow create: if isDuplicateEmail() && mergeUsers(userId);
}

但我在规则编辑器中看到一个错误:“意外的”}。第 40 行:

        let mergedData = {...existingUser, ...newUser};

我缺少什么? 谢谢。

安全规则表达式语言不支持像JavaScript这样的...展开运算符。事实上,它根本不是JavaScript——它只是看起来有点像JS。 您可能想在文档中阅读有关其语法的信息

最重要的是,没有 function 称为update 您根本无法修改安全规则中的数据。 您只能检查是否应允许或拒绝传入访问。 如果要修改文档数据,则必须为此编写应用程序或后端代码。

}正在关闭使用mergeUsers() function 的allow create语句之前的匹配语句。尝试:

   match /users/{userId} {
        allow create: if request.resource.data.email != null;
        allow update: if request.resource.data.email != null && request.auth.uid == userId;
        function isDuplicateEmail() {
            return get(/databases/$(database)/documents/users/$(request.resource.data.email)).exists;
        }
        function mergeUsers(userId) {
            // Get the data of the new user
            let newUser = get(/databases/$(database)/documents/users/$(userId)).data;
            
            // Get the data of the existing user
            let existingUser = get(/databases/$(database)/documents/users/$(newUser.email)).data;
            
            // Merge the data from the two users
            let mergedData = {...existingUser, ...newUser};
            
            // Update the data of the existing user
            return update(/databases/$(database)/documents/users/$(newUser.email), mergedData);
        }
        allow create: if !isDuplicateEmail()
        allow create: if isDuplicateEmail() && mergeUsers(userId);
    }

此外,如果您要使用update function,您还需要包含允许更新发生的规则。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM