Firebase安全规则并检查唯一记录

时间:2014-09-29 20:31:02

标签: angularjs firebase angularfire firebase-security firebasesimplelogin

我正在构建一个AngularjS应用,允许用户(使用Firebase匿名进行身份验证)提交他们的全名,公司和电子邮件地址,以便进入我们的分发列表。

我想要完成的是禁用用户表单两次输入数据,从而检查提交的数据是否已存在于数据库中。如果是这样,它应该拒绝提交的数据,保持我的数据库清洁。用户界面将处理所有错误消息,等等。

我的终点:http://someurl.firebaseio.com/accounts/

通过push()提交到/ accounts /的示例数据:

{fullName: "John Doe", company: "Pet's Place", email: "john@petsplace.org"}

Firebase安全规则设置:

目标:每个人都可以写入/ accounts /注册,只有唯一值和长度和isString的验证。匿名用户不允许阅读。

{
"rules": {
    ".read": "auth !== null",
    ".write": "auth !== null",
    "accounts": {
        ".write": "auth !== null && newData.exists()",
        "$accountID": {
            ".read": false,
            ".validate": "newData.hasChildren(['fullName', 'company', 'email'])",
            "fullName": {
                ".validate": "newData.isString() && newData.val().length > 0 && newData.val().length < 50 && !newData.val().contains('admin')"
            },
            "company": {
                ".validate": "newData.isString() && newData.val().length > 0 && newData.val().length < 50"
            },
            "email": {
                ".validate": "newData.isString() && newData.val().length > 0 && newData.val().length < 50"
            }
        }
    }
}
}

(多次)提交后的结果

{
"accounts" : {
"-JY249g70KL-XG0c6ekM" : {
  "company" : "Pet's Place",
  "email" : "john@petsplace.org",
  "fullName" : "John Doe"
},
"-JY249y2IwFWAYwEqC4Q" : {
  "company" : "Pet's Place",
  "email" : "john@petsplace.org",
  "fullName" : "John Doe"
},
"-JY24ACApcPH2_jiU5PD" : {
  "company" : "Pet's Place",
  "email" : "john@petsplace.org",
  "fullName" : "John Doe"
},
"-JY24AL8QOKQRiTh3Oqm" : {
  "company" : "Pet's Place",
  "email" : "john@petsplace.org",
  "fullName" : "John Doe"
}
}
}

1 个答案:

答案 0 :(得分:0)

通过将电子邮件地址用作密钥,您可以确保每个电子邮件地址只有一个条目:

var fbRef = new Firebase('https://someurl.firebaseio.com/');

// create a new user somehow
var newUser = {
    fullName: "John Doe", 
    company: "Pet's Place", 
    email: "john@petsplace.org"
}

// escape '.' because it can not be used as a key in FB
function escapeEmail(email){
    return email.replace(/\./g, ',');
}

fbRef.child('accounts').child(escapeEmail(newUser.email)).set(newUser, function(err) {
    if(err) {
        // if there was an error, the email address already exists
    }
);

然后在您的规则中验证密钥(电子邮件地址)尚不存在:

{
    "rules": {
        ".read": true,
        "accounts": {
            "$account": {
                ".write": true,
                ".validate": "!root.child('accounts').child(newData.child('email').val().replace(/\./g, ',')).exists()"
            }
        }
    }
}

另请参阅此处了解更多信息: What Firebase rule will prevent duplicates in a collection based on other fields? 和这里: How do you prevent duplicate user properties in Firebase?