Reputation: 501
I am logging my users in with the Facebook and Google sign-in protocols. I am able to store these users by doing:
let firebaseID = Auth.auth().currentUser?.uid
let userID = user.userID
let fullName = user.profile.name
let email = user.profile.email
let provider = "Google"
guard let authentication = user.authentication else {return}
let credential = GoogleAuthProvider.credential(withIDToken: authentication.idToken, accessToken: authentication.accessToken)
Auth.auth().signInAndRetrieveData(with: credential) { (authResult, error) in
if let error = error {
print("Failed to create Firebase User with Google: ", error)
return
}
print("Successful creation of Firebase User with Google")
let databaseRef = Database.database().reference()
let key = databaseRef.child("node").childByAutoId().key
let userInfo = ["UID": userID,
"Full Name": fullName,
"Email": email,
"Provider": provider]
let childUpdates = ["/Users/\(key)/": userInfo]
databaseRef.updateChildValues(childUpdates)
Every time I sign in, even with the same credentials a new user is created with the same sign in user. How can I prevent a new instance from being created if a particular user has logged in before.
Upvotes: 1
Views: 221
Reputation: 545
you should use:
let childUpdates = ["/Users/\(userID)/": userInfo]
and so that the optional does not appear you should put it like this:
let key = databaseRef.child("node").childByAutoId().key ?? ""
or unwrap it if you want to catch/prevent nil
let key = databaseRef.child("node").childByAutoId().key!
However, since the user id does not change when the same user enters new information, and you are using the autokey for every time the user enters, a new child is being created every time.
Upvotes: 2
Reputation: 51
You should check if user is already registered or no after signInAndRetrieveData:
Auth.auth().signInAndRetrieveData(with: credential) { (authResult, error) in
if let error = error {
return
}
if(isNewUser()) {
// create new user in Firebase
}
else {
// continue and skip creating user ..
}
}
Upvotes: 1