Firebase安全规则用于检查子项#AskFirebase的唯一值

时间:2016-08-25 15:28:28

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

enter image description here

我的firebase数据库的结构如上所示。如何确保网址是唯一的并且没有重复项?因为,这些是网址,我不能直接将它们用作路径,我被迫将它们用作值。所以像this这样的解决方案不会起作用。

1 个答案:

答案 0 :(得分:4)

如果您希望Firebase数据库中的某些内容是唯一的,则应将其存储为密钥。这自动保证了唯一性。

如您所述,某些字符不能用于密钥。在这种情况下,您需要对值进行编码,以便在密钥中允许它,以确保您不会丢失使值唯一的信息。一个非常简单的例子是当有人想在数据库中存储唯一的电子邮件地址时。由于密钥不能包含.个字符,因此我们需要对其进行编码。对此的常见编码是将.替换为,

users: {
  "uidOfPuf": {
    name: "Frank van Puffelen",
    email: "puf@firebaseui.com"
  }
},
emailAddresses: {
  "puf@firebaseui,com": "uidOfPuf"
}

使用,在电子邮件地址方面特别方便,因为电子邮件地址不能包含,

但总的来说,重要的是编码值是合理保证是唯一的"并且您仍然将实际值存储在某处(例如上面的/users/$uid/email)。

对于编码网址,我只是从剥离所有非法字符开始:

var url = "http://stackoverflow.com/questions/39149216/firebase-security-rules-to-check-unique-value-of-a-child-askfirebase";
ref.child(url.replace(/[\.\/]/g, '')).set(url);

商户:

"http:stackoverflowcomquestions39149216firebase-security-rules-to-check-unique-value-of-a-child-askfirebase": "http://stackoverflow.com/questions/39149216/firebase-security-rules-to-check-unique-value-of-a-child-askfirebase"

更新:我正在考虑是否为密钥使用简单的哈希码,从而导致更合理的长度密钥:

// from http://stackoverflow.com/questions/7616461/generate-a-hash-from-string-in-javascript-jquery
String.prototype.hashCode = function(){
    var hash = 0;
    if (this.length == 0) return hash;
    for (i = 0; i < this.length; i++) {
        char = this.charCodeAt(i);
        hash = ((hash<<5)-hash)+char;
        hash = hash & hash; // Convert to 32bit integer
    }
    return hash;
}

var url = "http://stackoverflow.com/questions/39149216/firebase-security-rules-to-check-unique-value-of-a-child-askfirebase";

ref.child(url.hashCode()).set(url);

导致:

20397229: "http://stackoverflow.com/questions/39149216/firebase-security-rules-to-check-unique-value-of-a-child-askfirebase"