首先,如果用户已经有一个username
,它是唯一的,而且这不会消失,我建议你放弃使用简单uid
的 login 。正如您在这里已经发现的那样,这只会产生试图在两者之间来回切换的问题。研究使用firebase-passport-login之类的工具创建自己的令牌,然后通过.username
但既然这不是你的问题,让我们在我们在这里的时候解决这个问题,因为你可能想继续前进,进入我多次经过的双重身份的荆棘荆棘。
要使用户名唯一,请存储用户名索引。
/users/$userid/username/$username
/usernames/$username/$userid
为确保它们是唯一的,请在 usernames/ 路径中的用户 ID 上添加如下安全规则,以确保每个用户名只能分配一个用户,并且该值是用户的 ID:
".write": "newData.val() === auth.uid && !data.exists()"
现在通过将以下内容添加到 users/ 记录中的用户名来强制它们匹配:
"users": {
"$userid": {
"username": {
".validate": "root.child('usernames/'+newData.val()).val() === $userid"
}
}
}
这将确保 id 是唯一的。小心读取权限。您可能希望完全避免这些,因为您不希望任何人查找私人电子邮件或用户名。像我展示的那样支持保存这些将是理想的。
这里的想法是您尝试分配用户名和电子邮件,如果它们失败,那么它们已经存在并且属于另一个用户。否则,您将它们插入到用户记录中,现在让用户按 uid 和电子邮件进行索引。
为了遵守 SO 协议,以下是该要点的代码,最好通过链接阅读:
var fb = new Firebase(URL);
function escapeEmail(email) {
return email.replace('.', ',');
}
function claimEmail(userId, email, next) {
fb.child('email_lookup').child(escapeEmail(email)).set(userId, function(err) {
if( err ) { throw new Error('email already taken'); }
next();
});
}
function claimUsername(userId, username, next) {
fb.child('username_lookup').child(username).set(userId, function(err) {
if( err ) { throw new Error('username already taken'); }
next();
});
}
function createUser(userId, data) {
claimEmail(userId, data.email, claimUsername.bind(null, userId, data.username, function() {
fb.child('users').child(userId).set(data);
);
}
和规则:
{
"rules": {
"users": {
"$user": {
"username": {
".validate": "root.child('username_lookup/'+newData.val()).val() === auth.uid"
},
"email": {
".validate": "root.child('email_lookup').child(newData.val().replace('.', ',')).val() === auth.uid"
}
}
},
"email_lookup": {
"$email": {
// not readable, cannot get a list of emails!
// can only write if this email is not already in the db
".write": "!data.exists()",
// can only write my own uid into this index
".validate": "newData.val() === auth.uid"
}
},
"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"
}
},
}
}