Swift中的Firebase用户名唯一性

时间:2016-11-15 20:48:58

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

我正在尝试在注册用户时检查用户名唯一性。我知道有很多关于它的问题,我经历了所有这些问题但是我的问题是它没有做任何事情,它没有打印出用户名存在且它甚至没有注册使用用户名。

我做错了什么?我似乎无法找到答案,唯一可能出错的是if nesting。

这是结构:

AppName:
    users
     1v2mRJTvrBQ7dMQohUU3rnn7ypI3: //UID
     username: John

这就是代码:

func registerUser(){
        guard let username = usernameField.text, let email = emailField.text, let password = passwordField.text else{
            print("Successfully registered")
            return
        }
        if connectedToNetwork() == true{
            if passwordField.text == confirmPasswordField.text{
                let usersRef = FIRDatabase.database().reference().child("users")
                usersRef.queryOrdered(byChild: "username").queryEqual(toValue: "\(username)")
                .observeSingleEvent(of: FIRDataEventType.value, with: { (snapshot) in
                    if snapshot.value is NSNull{

                AuthProvider.Instance.register(withEmail: email, password: password, username: username, loginHandler: { (errMessage) in
                    if errMessage != nil{

                    }else{
                        let user = FIRAuth.auth()?.currentUser
                        guard let uid = user?.uid else{
                            return
                        }
                        user?.sendEmailVerification() { error in
                            if let error = error {
                                print(error.localizedDescription)
                            } else {
                                print("Email has been sent to you!")
                            }
                        }
                        //User logged in and redirect

                    }
                })
                    }else{
                    print("Username already exists")// It doesn't execute this
                    }
                })
            }else{
                Util.errorAlert(message: "Passwords do not match!")
            }
        }else{
            Util.errorAlert(message: "The internet connection appears to be offline.")
        }
    }

我甚至尝试过不同的安全规则,但那些不应该有任何区别,但我使用的那些:

{ 
"rules": { 
".read": "auth != null", 
".write": "auth != null", 
"Snuses": { 
".indexOn": "Brand",
    "$username": {
        ".validate": "!root.child(users').hasChild($username)"
    }
} 
} 
}

我做错了什么?

3 个答案:

答案 0 :(得分:1)

您的问题出在您的安全规则中。您在用户通过身份验证之前正在进行查询。此查询将失败,因为您的规则声明必须对用户进行身份验证才能查询数据库(auth!= null)。

您需要做的是创建另一个名为“usernames”的子项。任何没有身份验证的人都可以读取。检查是否已使用用户名,如果没有,请为新用户申请。然后,执行您的身份验证呼叫并在“用户”子项中创建您的用户。

答案 1 :(得分:0)

对Firebase一无所知,“了解它正在做某事”的方式似乎是提醒或打印。因此,如果它没有这样做,我会看到至少两条执行路径不会以警报或打印结束。

if errMessage != nil{

guard let uid = user?.uid else{

这也可能缺少else,但我无法用足以回答S.O.的努力程度找到它。问题:

if snapshot.value is NSNull{

从理论上讲,你的Util.errorAlert也可能被打破。

答案 2 :(得分:0)

Firebase不允许重复的用户(名称),因此当您尝试创建用户时,只需查找错误。

FIRAuth.auth()?.createUser(withEmail: email, password: password) { (user, error) in
  // ...
}

可以返回4个错误:

FIRAuthErrorCodeInvalidEmail
     Indicates the email address is malformed.

FIRAuthErrorCodeEmailAlreadyInUse  (this is the one to address you question)
     Indicates the email used to attempt sign up already exists. Call 
     fetchProvidersForEmail to check which sign-in mechanisms such
     user used, and prompt the user to sign in with one of those.

FIRAuthErrorCodeOperationNotAllowed
     Indicates that email and password accounts are not enabled. Enable them in the
     Authentication section of the Firebase console.

FIRAuthErrorCodeWeakPassword
     Indicates an attempt to set a password that is considered too weak. The 
     NSLocalizedFailureReasonErrorKey field in the NSError.userInfo
     dictionary object will contain more detailed explanation that can
     be shown to the user.