2

我想防止重複的用戶名,而signUp形式的用戶輸入。我已經創建瞭如下的電子郵件登錄名,然後創建用戶然後用用戶字典授權setValue。如何防止用戶名在Firebase中重複註冊?

但是我堆疊Firebase安全設置以及如何檢查處理這種情況。

REF_BASE.createUser(email, password: pwd, withValueCompletionBlock: { .. 

REF_BASE.authUser(email, password: pwd, withCompletionBlock: { .. 

REF_USERS.childByAppendingPath(uid).setValue(user) 

該處理總是響應錯誤。

REF_USERS.childByAppendingPath(uid).childByAppendingPath("username").setValue(user["username"]) { (error: NSError!, result: Firebase!) in 
      if error != nil { 
       print(error.localizedDescription) 
      } 
      else { 
       self.REF_USERS.childByAppendingPath(uid).setValue(user) 
      } 
     } 

這是我的安全規則,我如何修復一切以防止重複的用戶?

"users": { 
     ".read": "auth !== null", 
     "$user": { 
      "username": { 
       ".read": "auth !== null", 
       ".write": "newData.val() === auth.uid && !data.exists()" 
      } 
     } 
    }, 

更新:

從弗蘭克的答案,但我不知道我需要在這種情況下,迅速做而註冊新用戶。

app : { 
    users: { 
     "some-user-uid": { 
      email: "[email protected]" 
      username: "myname" 
     } 
    }, 
    usernames: { 
     "myname": "some-user-uid" 
    } 
} 

需要我爲兩個不同的節點同時添加相同的用戶uid?如果有人在Swift中解釋它。這會很棒。

"users": { 
    "$uid": { 
    ".write": "auth !== null && auth.uid === $uid", 
    ".read": "auth !== null && auth.provider === 'password'", 
    "username": { 
     ".validate": " 
     !root.child('usernames').child(newData.val()).exists() || 
     root.child('usernames').child(newData.val()).val() == $uid" 
    } 
    } 
} 

不能信息添加新用戶的用戶名節點。它需要另一個安全規則?

+0

你準確得到了什麼錯誤? –

+0

我得到[Firebase] setValue:或removeValue:at/users/8372c890-112d-4a75-924c-98814ea15963 /用戶名失敗:permission_denied – tobeiosdev

+0

第一點是您的第二個.read規則已過時,因爲[rules cascade](https ://www.firebase.com/docs/security/guide/securing-data.html#section-cascade)。對於錯誤我不完全確定,但它看起來像你試圖寫一個用戶到firebase,並在你的規則中,你只允許該值爲uid(newData.val()=== auth.uid) –

回答

0

如果您試圖阻止重複Firebase用戶名,可以在createUser階段完成。

假設一個對話框提供給新用戶,要求創建一個帳戶:這將獲得他們想要的用戶名和密碼。

發送,爲的createUser,如果有一個錯誤(因爲它已經存在)通知他們,並要求不同的用戶名:用戶創建你可能會增加他們的信息的/用戶節點之後

myRootRef.createUser(email, password: pw, withValueCompletionBlock: { error, result in 

     if error != nil { 
      self.errMsgField.stringValue = "email/username in use, try again" 

     } else { 
      let uid = result["uid"] as! String //the uid of the new user 
      print("user created as \(uid)") 
      self.authUserWithAuthData(email, password: pw) //auth the user 
     } 
    }) 

以及。