2

我正在构建一个AngularjS应用程序,允许用户(使用Firebase匿名进行身份验证)提交其全名,公司和电子邮件地址以获取我们的通讯组列表。Firebase安全规则并检查唯一记录

我想完成的是禁用用户表单两次输入数据,因此检查提交的数据是否已经存在于数据库中。当它的时候,它应该拒绝提交的数据,保持我的数据库清洁。 UI将处理所有错误消息等。

我的终点:/提交/账户http://someurl.firebaseio.com/accounts/

采样数据通过推送():

{fullName: "John Doe", company: "Pet's Place", email: "[email protected]"} 

火力地堡安全规则设置:

目标:每个人都可以写/ 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" : "[email protected]", 
    "fullName" : "John Doe" 
}, 
"-JY249y2IwFWAYwEqC4Q" : { 
    "company" : "Pet's Place", 
    "email" : "[email protected]", 
    "fullName" : "John Doe" 
}, 
"-JY24ACApcPH2_jiU5PD" : { 
    "company" : "Pet's Place", 
    "email" : "[email protected]", 
    "fullName" : "John Doe" 
}, 
"-JY24AL8QOKQRiTh3Oqm" : { 
    "company" : "Pet's Place", 
    "email" : "[email protected]", 
    "fullName" : "John Doe" 
} 
} 
} 

回答

0

通过使用电子邮件地址作为一个键,就可以确保只会有一个每个电子邮件地址条目:

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

// create a new user somehow 
var newUser = { 
    fullName: "John Doe", 
    company: "Pet's Place", 
    email: "[email protected]" 
} 

// 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?

+0

坦克您的回复,我也会试一试。将发布我的调查结果回到这里。 – svh1985 2014-10-14 11:42:39

+0

@magicMaker,那些验证规则不适用于当前的Firebase'''导致您无法保存的错误。 – 2016-11-22 10:37:56