Authenticate user (Facebook) with Firebase

2

I am trying to authenticate my registered users through Facebook in Firebase. But the Firebase documentation is in objective-C and I'm working with Swift.

I have already created the app from Facebook and authenticated by Facebook on the Firebase dashboard.

I already have the authentication part with Facebook, the following fragment of code extracted from the Firebase documentation:

  

To log a user in, we'll need to retrieve the OAuth Access Token from   Facebook. Once we have the access token, we can use   authWithOAuthProvider: token: withCompletionBlock: to authenticate the   user with Firebase. Below is one way to get an access token with read   permissions from the Facebook SDK.

In half translated Spanish it says:

  

To register a user, we will have to recover OAuth access   symbolic of Facebook. Once we have the access token, we can   use authWithOAuthProvider: token: withCompletionBlock: to   authenticate the user with Firebase. Below is a   way to get an access token with read permissions from the   SDK of Facebook.

class LoginViewControllerMaster: UIViewController{

    var ref: Firebase!
    //var loginView : FBSDKLoginButton = FBSDKLoginButton()

    @IBAction func LoginFacebook(sender: AnyObject) {

        ref = Firebase(url: "https://myapp.firebaseio.com/")
        let facebookLogin = FBSDKLoginManager()

        facebookLogin.logInWithReadPermissions(["public_profile", "email", "user_friends","user_birthday"], fromViewController : self , handler: {
            (facebookResult, facebookError) -> Void in

            if facebookError != nil {
                print("Facebook login failed. Error \(facebookError)")
            } else if facebookResult.isCancelled {
                print("Facebook login was cancelled.")
            } else {
                let accessToken = FBSDKAccessToken.currentAccessToken().tokenString
                self.ref.authWithOAuthProvider("facebook", token: accessToken,
                    withCompletionBlock: { error, authData in
                        if error != nil {
                            print("Login failed. \(error)")
                        } else {
                            print("Logged in! \(authData)")
                        }
                })
            }
        })

    }

    @IBAction func LogoutFacebook(sender: AnyObject) {
//        let loginManager = FBSDKLoginManager()
//        loginManager.logOut() // this is an instance function
        print("Voy de salida")


    }
}

Up to here everything is perfect. From the previous code, the key part as I understand it is here:

let accessToken = FBSDKAccessToken.currentAccessToken().tokenString
                self.ref.authWithOAuthProvider("facebook", token: accessToken,
                    withCompletionBlock: { error, authData in
                        if error != nil {
                            print("Login failed. \(error)")
                        } else {
                            print("Logged in! \(authData)")
                        }
                })

However, from here I do not see what path to follow to achieve logging my users in Firebase. There are many examples on the web of how to login with username and password, but social networks almost nothing.

I thank you in advance for your kind support.

    
asked by Víctor Gonzal 21.02.2016 в 06:00
source

1 answer

4

I have continued searching and I have arrived at the following solution. It is likely that you can optimize and improve it but for now it has worked. I hope someone serves you.

@IBAction func LoginFacebook(sender: AnyObject) {

ref = Firebase(url: "https://Myapp.firebaseio.com/")
let facebookLogin = FBSDKLoginManager()

facebookLogin.logInWithReadPermissions(["public_profile", "email", "user_friends","user_birthday"], fromViewController : self , handler: {
    (facebookResult, facebookError) -> Void in

    if facebookError != nil {
        print("Facebook login failed. Error \(facebookError)")
    } else if facebookResult.isCancelled {
        print("Facebook login was cancelled.")
    } else {


        let accessToken = FBSDKAccessToken.currentAccessToken().tokenString
        self.ref.authWithOAuthProvider("facebook", token: accessToken,
            withCompletionBlock: { error, authData in
                if error != nil {
                    print("Login failed. \(error)")
                } else {
                    print("Logged in! \(authData)")
                    print ("Access Token \(accessToken)")
                    //INICIA PROCESO DE RECUPERACION DE CAMPOS
                    let graphRequest : FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me", parameters: ["fields":"id,interested_in,gender,birthday,email,age_range,name,picture.width(480).height(480)"])
                    graphRequest.startWithCompletionHandler({ (connection, result, error) -> Void in

                        if ((error) != nil)
                        {
                            // Process error
                            print("Error: \(error)")
                        }
                        else
                        {
                            //print("fetched user: \(result)")
                            let id : NSString = result.valueForKey("id") as! String
                            print("User ID is: \(id)")
                            let correo : NSString = result.valueForKey("email") as! String
                            print("EL Correo es \(correo))")
                            //etc...
                            // INICIA CREACION Y AUTENTICACION DE USUARIO EN FIREBASE
                            // 1
                            self.ref.createUser(correo as String, password: String(authData)) { (error: NSError!) in
                                // 2

                                if error == nil {
                                    // 3

                                    self.ref.authUser(accessToken, password: String(authData),
                                        withCompletionBlock: { (error, auth) -> Void in
                                            print("Creado")
                                            // 4
                                    })
                                }
                                else
                                {
                                    print("hay errores. \(error)")
                                }
                            }
                            //TERMINA CREACION Y AUTENTICACION DE USUARIO EN FIREBASE
                        }
                    })
                    //TERMINA PROCESO DE RECUPERACION DE CAMPOS

                                            }
        })
    }
})

}
    
answered by 21.02.2016 в 22:58