如果数据库中已经存在该用户,则拒绝创建该用户

时间:2018-11-11 14:34:59

标签: swift firebase firebase-realtime-database

我是使用Firebase的新手,我目前正在为我的学校制作一个应用程序,以允许父母通过该处支付每月的费用,但是我面临两个问题,我有一个孩子(usernames / $ usernames / $ uid),它标识用户是否已经存在,我还有另一个(用户/详细信息/ $ uid / $ username),而这个不能标识$ username是否存在,我该如何解决?

我的另一个问题是,即使(usernames / $ usernames / $ uid)知道重复,Auth仍会创建用户。如何使Auth识别用户是否已经重复并且拒绝创建新用户?

谢谢。 我的下面的代码

@IBAction func signUp(_ sender: Any) {
        ref = Database.database().reference()

        let alert = UIAlertController(title: "Registrarse", message: "Por favor, introduce tu información", preferredStyle: .alert)

        let saveAction = UIAlertAction(title: "Crear Cuenta", style: .default) { action in
            let emailField = alert.textFields![0]
            let userField = alert.textFields![1]
            let passwordField = alert.textFields![2]

        Auth.auth().createUser(withEmail: emailField.text!, password: passwordField.text!) { user, error in
            if error != nil {

            } else {
                let uid = Auth.auth().currentUser!.uid
                let ref = Database.database().reference()
                let usersReference = ref.child("usernames")
                let values = [userField.text : uid]

                self.ref.child("users/details").child(uid).setValue(["username" : userField.text!, "email" : emailField.text!, "creationDate" : String(describing: Date())])

                usersReference.child(userField.text!).observeSingleEvent(of: .value, with: { (snapshot) in
                    if snapshot.exists() {
                        print ("taken")
                    } else {
                        print ("free")
                    }

                    usersReference.updateChildValues(values)
                }
            )}
        }
        }

        let cancelAction = UIAlertAction(title: "Cancelar", style: .default)

        alert.addTextField { textEmail in
            textEmail.placeholder = "Correo Electrónico"
        }
        alert.addTextField { userField in
            userField.placeholder = "Usuario"
        }
        alert.addTextField { textPassword in
            textPassword.isSecureTextEntry = true
            textPassword.placeholder = "Contraseña"
        }

        alert.view.transform = CGAffineTransform(translationX: 2, y: 2)
        alert.addAction(saveAction)
        alert.addAction(cancelAction)

        present(alert, animated: true, completion: nil)
    }

1 个答案:

答案 0 :(得分:1)

var ref: DatabaseReference { return Database.database().reference() }
var usernamesRef: DatabaseReference { return ref.child("usernames") }

创建用户之前,您需要检查用户名是否已被使用。

func checkExistingUsernames(forUsername username: String, withExists: @escaping (Bool) -> ()) {
    usernamesRef.child(username).observeSingleEvent(of: .value, with: { (snapshot) in
        withExists(snapshot.exists())
    })
}

然后,您可以更新用户名和新创建的用户的详细信息。

func createUserDetails(forUser user: User, withUsername username: String, completion: @escaping (Error?) -> ()) {
    ref.updateChildValues([
        "usernames/\(username)": user.uid,
        "users/details/\(user.uid)": [
            "username" : username,
            "email" : user.email,
            "creationDate" : String(describing: Date())
        ]
    ]) { (error, ref) in
        completion(error)
    }
}

因此,我们检查用户名是否已经存在,并创建一个用户,并详细说明用户名是否可用。

class UsernameAlreadyExistsError: Error {}

func createUser(withUsername username: String, email: String, password: String, completion: @escaping (User?, Error?) -> ()) {
    checkExistingUsernames(forUsername: username) { [weak self] alreadyExists in
        if alreadyExists {
            completion(nil, UsernameAlreadyExistsError())
        } else {
            Auth.auth().createUser(withEmail: email, password: password) { [weak self] (result, error) in
                if let user = result?.user {
                    self?.createUserDetails(forUser: user, withUsername: username) { (error) in
                        completion(user, error)
                    }
                } else {
                    completion(nil, error)
                }
            }
        }
    }
}

最后,在保存操作中,您可以致电createUser

let saveAction = UIAlertAction(title: "Crear Cuenta", style: .default) { [weak self] action in
    guard
        let email = alert.textFields?[0].text,
        let username = alert.textFields?[1].text,
        let password = alert.textFields?[2].text else { return }

    self?.createUser(withUsername: username, email: email, password: password) { (user, error) in
        if let error = error {
            print("create user", error)
        } else if let user = user {
            print("user created", user)
        }
    }
}