Facebook login using Firebase - Swift iOS - ios

I'm implementing login with Facebook using Firebase, I have this code which searches my database after a successful facebook authentication for the email if exists in database and logs in the app if found, I want to direct the user to registration view controller if not found but its not working since this method is asynchronous. I appreciate if anyone can help. Here is my code :
func getFacebookUserInfo() {
if(FBSDKAccessToken.current() != nil){
let graphRequest = FBSDKGraphRequest(graphPath: "me", parameters: ["fields" : "id,name,gender,email,education"])
let connection = FBSDKGraphRequestConnection()
connection.add(graphRequest, completionHandler: { (connection, result, error) -> Void in
let data = result as! [String : AnyObject]
let email = data["email"] as? String
let emailRef = FIRDatabase.database().reference().child("usernameEmailLink")
emailRef.queryOrderedByValue().observe(.childAdded, with: { snapshot in
if let snapshotValue = snapshot.value as? [String: AnyObject] {
for (key, value) in snapshotValue {
if(value as? String == email){
self.stringMode = snapshotValue["mode"]! as! String
self.username = key
self.parseUserInfoFromJSON()
return
}
}
}
})
})
connection.start()
}
}
Thank you.

The registration/existence of the user in Firebase should probably be determined before the graphRequest code in the question.
Most importantly, (and this is critical), email addresses are dynamic so they should not be used to verify if a user exists. i.e. user with email address of 'leroy#gmail.com' updates his email to 'leroy.j#gmail.com'. If emails are used to verify registration, it can totally break if that email changes.
Please use Firebase uid's for that purpose as they are static and unique.
Since we only have a small snippet of code, we don't know the exact sequence being used. This answer is pseudo-code to outline a possible sequence.
We assume that by 'registered' it means that the user has gone through some kind of app registration sequence and the user has been created (and now exists/is registered) in Firebase.
In general there would be a login button and a delegate method to handle the actual login action.
The user enters their login and taps the login button
func loginButton(loginButton: FBSDKLoginButton!,
didCompleteWithResult result: FBSDKLoginManagerLoginResult!,
error: NSError?) {
Firebase can then get the credentials for that user (see Firebase doc quote below)
let credential = FIRFacebookAuthProvider.credential(withAccessToken: FBSDKAccessToken.current().tokenString)
At that point, sign in the user and check to see if they are registered (exist) in the Firebase user node.
FIRAuth.auth()?.signIn(with: credential) { (user, error) in
if let error = error { //failed due to an error
return
}
let uid = user.uid //the firebase uid
let thisUserRef = userRef.child(uid) //a reference to the user node
//check to see if the user exists in firebase (i.e. is Registered)
thisUserRef.observeSingleEvent(of: .value, with: { (snapshot) in
//if snapshot exists
//then the user is already 'registered' in the user node
// so continue the app with a registered user
//if not, then need to have the user go through a registration sequence and
// then create the user (make them registered) in the user node
doRegisterUser(user)
})
func doRegisterUser(user: FIRUser) {
//get what you need from the user to register them
// and write it to the users node. This could be from additional
// questions or from their Facebook graph, as in the code in the
// question
//for this example, we'll just write their email address
let email = user.email
let dict = ["email": email]
//create a child node in the users node with a parent of uid
// and a child of email: their email
thisUserRef.setValue(node)
//next time the user logs in via FB authentication, their user node
// will be found as they are now a 'registered' user
}
From the Firebase docs
After a user signs in for the first time, a new user account is
created and linked to the credentials—that is, the user name and
password, or auth provider information—the user signed in with. This
new account is stored as part of your Firebase project, and can be
used to identify a user across every app in your project, regardless
of how the user signs in.
As I mentioned, this is very pseudo code but offers a possible sequence for a solution.

Related

why do i get two user ids when creating a user in firebase using swift?

when i sign up a user in my ios app it generates a user id and adds that to the data base with the users name and surname and username but it is generating a user id and another random number/id and i dont know what that is for:
i dont know what the Roy... is and dont know where its coming from.
so when i try and access the users uid to access the information such as the name and surname i keep getting the following error because its using the wc7... number and not the other one:
Listener at /Users/wc7VyejKlDNfcAhFu3AkIX9Y9on1/Username failed: permission_denied
this is my code that i use to try and access the users information:
func fetchUsersData() {
guard let currentUser = Auth.auth().currentUser?.uid else { return }
print("Current user id is \(currentUser)")
Database.database().reference().child("Users").child(currentUser).child(USER_NAME).observeSingleEvent(of: .value) { (snapshot) in
guard let username = snapshot.value as? String else {return}
self.navigationItem.title = username
}
}
how do i fix this?
That code is for the Firebase Real Time Database and the screen shot is for Cloud Firestore. They are totally different and unrelated.
If you want to read the data shown in your screenshot you need to use the Cloud Firestore documentation.
The documentID 'Roy...' happens when you don't assign a document an ID... it will generate one automatically.
Also, change your Firestore structure to use the users uid as the documentID. So it would look like this
users //the collection
uid_0 //the document with documentID = a users uid
first_name: "Hank"
last_name: "Jones"
user_name: "Hankster"
uid_1
first_name: "Leroy"
last_name: "Jenkins"
user_name: "Leeeerrroooyyy"
and then the code to read a specific user name based on a uid is this
func readUserName() {
let users = self.db.collection("users")
let thisUser = users.document(the users uid)
thisUser.getDocument(completion: { documentSnapshot, error in
if let error = error {
print(error.localizedDescription)
return
}
guard let snap = documentSnapshot else { return }
let docId = snap.documentID
let userName = snap.get("user_name") as? String ?? "No Name"
print(userName)
})
}
Also note that you will need to be authenticated to Firestore to read any data or adjust the Security Rules to allow anyone to read. That's not generally a good idea but when you're just getting started it's ok.

Swift Firebase -How can I verify the `PhoneAuthCredential` and keep the user currently signed in with their current email uid

Users sign into my app with email authentication. Once inside they can browse and search for different things. But if the user wants to post they have to verify their phone number (if they don't want to post their phone number isn't necessary).
The phone number and sms process works fine but once I authenticate the PhoneAuthCredential the uid associated with the email that the user is currently signed in with is replaced with the uid generated from the phone credential. This creates a situation where an entirely new user is inside the app and because of this they don't have access to any of their data (anything associated with the uid from the email).
Basically the Auth.auth().currentUser?.uid was initially the email's uid and now the Auth.auth().currentUser?.uid would be the phone's uid
How can I verify the PhoneAuthCredential and keep the user currently signed in with their current email uid?
var emailUid: String? // a6UVVWWN4CeTCLwvkn...
var verificationId: String?
var phoneUid: String? // tUi502DnKlc19U14xSidP8
// 1. user signs into the app with their email address and their uid is a6UVVWWN4CeTCLwvkn...
Auth.auth().signIn(withEmail: emailTextField.text!, password: self.passwordTextField.text!, completion: {
(authDataResult: AuthDataResult?, error) in
self.emailUid = authDataResult?.user.uid // a6UVVWWN4CeTCLwvkn...
})
// 2. user goes to post something but before they can post they have to verify their phone number
PhoneAuthProvider.provider().verifyPhoneNumber(phoneNumberTextfield.text!, uiDelegate: nil) {
(verificationID, error) in
guard let verificationID = verificationID else { return }
self.verificationId = verificationID
}
// 3. sms code is sent to user's phone and they enter it
let credential = PhoneAuthProvider.provider().credential(withVerificationID: verificationId!, verificationCode: smsTextField.text!)
// 4. now VERIFY sms code by signing the user in with the PhoneAuthCredential
Auth.auth().signInAndRetrieveData(with: credential, completion: {
(authDataResult, error) in
self.phoneUid = authDataResult?.user.uid // tUi502DnKlc19U14xSidP8 this is now the current user's uid
// 5. save phoneNumber and verificationId to the user's uid ref associated with the EMAIL address
var dict = [String: Any]()
dict.updateValue(verificationId!, forKey: "verificationId")
dict.updateValue(phoneNumberTextfield.text!, forKey: "phoneNumber")
dict.updateValue(self.phoneUid!, forKey: "phoneUid")
if Auth.auth().currentUser!.uid == self.emailUid! {
// THIS WILL NEVER RUN
let emailUidRef = Database.database().reference().child("users").child(emailUid!)
emailUidRef?.updateChildValues(dict)
}
})
You can link the two accounts together using Firebase Authentication's account linking. As that documentation says:
Complete the sign-in flow for the new authentication provider up to, but not including, calling one of the FirebaseAuth.signInWith methods.
So you skip signInAndRetrieveData(with: credential), but instead call User.linkAndRetrieveData(with: credential). Once the accounts are linked, you can sign in with either of them to get the "combined" authenticated user.

Firebase Not Capturing Email/Phone from Facebook

When a user logs into the app using Facebook, I am able to capture and display their full name; however, neither email nor phone number is coming across. I have tried both the "One account per email address" as well as "Multiple accounts per email". I have tested it with an account whose email address is definitely not already registered in Firebase. What am I missing such that email/phone are not being captured? This all does work with Google accounts.
let name = Auth.auth().currentUser?.displayName // works!
let email = Auth.auth().currentUser?.email // nil- why?
let phone = Auth.auth().currentUser?.phoneNumber // nil -why?
The login process, which is standard Firebase w/ Facebook, looks like this:
func loginButton(_ loginButton: FBSDKLoginButton!, didCompleteWith result: FBSDKLoginManagerLoginResult!, error: Error!)
{
if let error = error
{
print(error.localizedDescription)
}
else
{
if FBSDKAccessToken.current() != nil
{
let credential = FacebookAuthProvider.credential(withAccessToken: FBSDKAccessToken.current().tokenString)
Auth.auth().signIn(with: credential) { (user, error) in
if let error = error
{
print (error.localizedDescription)
}
}
}
}
}
To update based on comments below. The following also produces a nil email and phone when inspecting the contents of userInfo. I understand the phone might just be that way, but it seems the email was supposed to work.
let userInfo = Auth.auth().currentUser?.providerData
The top level phoneNumber currentUser.phoneNumber is only for Firebase verified phone numbers. If you have that Facebook phone number, you can use the currentUser.updatePhoneNumber API to verify that number (you will need to go through the whole flow). Otherwise, you can wait for the upcoming Admin node.js API to set phone numbers with Admin privileges on existing users: https://github.com/firebase/firebase-admin-node/commit/68563c4b2c8128fbc45fc65bad3f6730d320b539
As for the email, in the case of "multiple accounts per email" you need to set it yourself via currentUser.updateEmail. You can get the Facebook email from currentUser.providerData which contains the Facebook provider data.

How to add a username to Firebase database upon registration?

Upon logging in I want my app to make a new field in the Firebase database with the child named after the username.
if let email = emailField.text, let pass = passwordField.text {
// Check if it's sign in or register
if isLogin {
// Sign in the user with Firebase
Auth.auth().signIn(withEmail: email, password: pass, completion: { (user, error) in
// Check that user isn't nil
if let u = user {
// User is found, go to home screen
self.ref?.child(email).childByAutoId().setValue("1")
self.performSegue(withIdentifier: "goHome", sender: self)
print("yes")
}
When I try to do this, it gives me an error called SIGABART which I believe is associated with not having segues connected properly.
Yet if I delete this line:
self.ref?.child(email).childByAutoId().setValue("1")
or change the email field to a random string like "test", it works fine and appears in Firebase.
If I remember correctly, you can't use symbol # in nodes names. It's first problem. You can do it another, I think better, way:
You need to create user to ref like:
/users/uid from created FIRUser.
You can do it with next steps:
For example, your registration page will have 3 UITextFields: userEmail, userLogin and userPassword.
// *1* Create user
FIRAuth.auth()!.createUser(withEmail: userEmail.text!,
password: userPassword.text!)
{ user, error in
if error == nil {
// *2* Then log him in
FIRAuth.auth()!.signIn(withEmail: self.userEmail.text!,
password: self.userPassword.text!)
{ result in
// *3* Create new user in database, not in FIRAuth
let uid = (FIRAuth.auth()?.currentUser?.uid)!
let ref = FIRDatabase.database().reference(withPath: "someStartPart/users").child(uid)
ref.setValue(["uid": uid, "email": userEmail.text!, "login": userLogin.text!, "creationDate": String(describing: Date())])
self.performSegue(withIdentifier: "fromRegistrationToMainPage", sender: self)
}
} else {
print("\(String(describing: error?.localizedDescription))")
}
}
Like this. Hope it helps.
Firebase Auth will not allow you to store such a value. You will need to save this into Firebase Database or another service. e.g. In the Firebase Database:
userRef.setValue("username123")
You should save the username value in the database. Something like this:
FIRdatabase.database().reference().child("yourchildname").updateChild(u)
(Im on my phone, so the call might not be EXACTLY like that, but should be very close)
Cheers.
Swift 4:
//***** for realTime database
let ref = Database.database().reference(fromURL: "https://add your project URL")
let userRef = ref.child("users").child(user.user.uid)
let values = ["Email": email, "UserName": userName] //userName is the name of textField

XCode - Swift - Facebook Authentication with Parse

I have Facebook authentication integrated with parse using the following code:
PFFacebookUtils.logInInBackgroundWithReadPermissions(permissions) {
(user: PFUser?, error: NSError?) -> Void in
if let user = user {
if user.isNew {
let graphRequest : FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me", parameters: nil)
graphRequest.startWithCompletionHandler { (connection, result, error) -> Void in
user["email"] = result.valueForKey("email") as! String
user["firstName"] = result.valueForKey("first_name") as! String
user["lastName"] = result.valueForKey("last_name") as! String
user.saveInBackgroundWithBlock { (success: Bool, error: NSError?) -> Void in
// goto app
}
}
} else {
// goto app
}
} else {
// Canceled
}
}
So I use Parse's PFFacebookUtils to login the user, then add the extra fields email, firstName and lastName based on the user's Facebook info, then I log the user in. Just wondering if this is the right way to go about adding those additionals fields, and I was also wondering if there was a way to stop an email confirmation from going out in this scenario? I have a register via email option so I need email confirmation, but just not for Facebook login.
Yes as far as I know that is the correct way to set new field. Maybe you want to check for nil in the optionals instead of explicitly unwrapping like that?
And no I think every time you set the email on a PFUser it will send the authentication email if you have that option on in Parse.
One option to save the email without notifying them is to create your own emailId field and set it to that so that they don't get an email asking for authentication and when signing up a new user with email you can also set that field to be the same emailId (it is kind of messy cause you have the same value repeated) but its a workaround worth trying.

Resources