2016-12-29 51 views
0

我正在嘗試驗證用戶輸入的用戶名是否已被佔用。該代碼目前檢查電子郵件是否正在使用,並創建用戶,如果他們不存在。我怎樣才能使這個數據庫讀取,看看用戶名是否已被使用?如果用戶名已被佔用,請檢查Firebase數據庫

FIRAuth.auth()?.createUser(withEmail: email!, password: password!) { (user, error) in 
    if error?._code == (FIRAuthErrorCode.errorCodeInvalidEmail.rawValue) 
    { 
     var ref: FIRDatabaseReference! 
     ref = FIRDatabase.database().reference() 
     ref.child("Users").observeSingleEvent(of: FIRDataEventType.value, with: { (snapshot) in 

      if snapshot.hasChild(name!){ 
       ref.child("users").child((user?.uid)!).setValue(["username": name]) 
       print("true rooms exist") 
      } else { 
       self.displayMyAlertMessage(userMessage: "Username already in use. Please choose another.") 
       print("false room doesn't exist") 
      } 
     }) 
    } else { 
     self.displayMyAlertMessage(userMessage: "Email already in use. Please see the login page.") 
     return 
    } 
} 
+0

嗯,這不是「像寫」你的數據庫後端?你指的是'the'數據庫,哪一個?你有任何代碼寫入永久存儲? – Yohst

+0

我正在使用firebase,因此數據庫已經存在。代碼存儲的代碼是ref.child的代碼。 – AlexGarlock

+0

這已被問過「幾次」之前。請參閱[這些答案](http://stackoverflow.com/search?q=%5Bfirebase-database%5D%5Bios%5D+unique+username)或[來自加藤的原始答案](http://stackoverflow.com/問題/ 25294478/how-do-you-prevent-duplicate-user-properties-in-firebase)(對於JavaScript,但所有平臺的邏輯都是相同的)。 –

回答

1

你可以做的事情是創造另一個孩子如「takenUsernames」,存儲所有的用戶名在那裏。就這樣,即使用戶未通過身份驗證,您也可以檢查用戶是否被帶走。您還必須將規則添加到數據庫中。

的數據庫規則:

"takenUsernames": { 
     ".read": true, 
     ".write": "auth != null", 
     "$username": { 
     ".validate": "!root.child('takenUsernames').hasChild($username)" 
     } 
     } 

而且在斯威夫特可以做到這樣的,其中用戶名是從文本框的值。它基本上只是需要用戶名和檢查,如果這在takenUsername孩子的存在與否:

let usernamesRef = FIRDatabase.database().reference().child("takenUsernames") 
       usernamesRef.child(username).observeSingleEvent(of: .value, with: { (snapshot) in 
        if snapshot.exists() { 
         //Username is already taken 
        } else { 
         //Username doesn't exist, do your stuff 
} 

現在,每當您註冊用戶時,你必須添加鍵值對到takenUsernames孩子。在我的情況下,我這樣做:

usernamesRef.updateChildValues([username:uid]) 

我希望你明白了。

+0

我認爲安全規則需要更多的安全功能。使用當前的安全設置,用戶可能會覆蓋其他用戶名,而不是他們自己的用戶名。 –

+0

我明白了。幾乎在兩個地方存儲用戶名。不知道用戶在檢查用戶名是否存在時可以覆蓋其他用戶名。感覺我現在就像是PlayStation,不讓用戶更改他們的用戶名LOL – AlexGarlock

+0

如果我們想在用戶首次通過身份驗證之前做到這一點,該怎麼辦? – waseefakhtar

相關問題