Facebook login and Registration in same step

4

I have the following situation:

  • The service I have is half functioning. I did not do it, so I want to modify it a bit so that I do two steps in one, that is, currently when I click on the button that I have for Facebook it only registers but. he does not login I've never touched the facebook api so I do not know where to start ...

  • I have the following: I use a javascript file that contains the functions that the action of the button occupies.

    function FacebookAuthService(config) {
        var self = this;
        this.logged = false;
    
        this.init = function () {
            FB.init({
                appId: config.fbappId,
                cookie: true,
                status: true,
                xfbml: config.fbxfbml,
                version: config.fbversion
            });
            FB.Event.subscribe('auth.authResponseChange', self.userStatusChange);
        };
    
        function fbLogin(perms, callback) {
            perms = perms || '';
            FB.login(function (response) {
                if (response.status === 'connected') {
                    return callback({logged: true, uid: FB.getUserID()});
                }
                return callback({logged: false});
            }, {scope: perms});
        }
    
        this.userStatusChange = function (response) {
            self.logged = (response.status === 'connected');
        };
    
        this.login = function (perms, callback) {
            //if (!self.logged) {
                fbLogin(perms, callback);
            //} else {
            //    callback({logged: true, uid: FB.getUserID()});
            //}
        };
    
        this.getToken = function () {
            return FB.getAccessToken();
        };
    }
    /**
     * Service for Facebook Graph API
     *
     * @constructor
     */
    function FacebookGraphService() {
        /**
         * Calls to graph API
         *
         * @param path
         * @param params
         * @param callback
         */
        this.graph = function (path, params, callback) {
            params = params || {};
            FB.api(path, params, function (response) {
                var status = (response && !response.error);
                callback(status, response);
            });
        };
    }
    /**
     * Service for facebook user
     *
     * @constructor
     */
    function FacebookUserService() {
        /**
         * @type {FacebookGraphService}
         */
        var graphService = new FacebookGraphService();
        /**
         * Returns user's info
         *
         * @param uid
         * @param callback
         */
        this.getUserInfo = function (uid, callback) {
            uid = uid || 'me';
            graphService.graph('/' + uid, {fields: 'id,first_name,last_name,email'}, callback);
        };
    }
    
  • Inside the page where I load the content I have a script that generates the facebook sdk and initialize the main function

     <script type="text/javascript">
       // Load the SDK asynchronously
       (function (d, s, id) {
            var js, fjs = d.getElementsByTagName(s)[0];
            if (d.getElementById(id)) return;
            js = d.createElement(s);
            js.id = id;
            js.src = "//connect.facebook.net/en_US/sdk.js";
            fjs.parentNode.insertBefore(js, fjs);
       }(document, 'script', 'facebook-jssdk'));
         var fbAuthService = {};
         window.fbAsyncInit = function () {
         fbAuthService = new FacebookAuthService(globalServerData);
         fbAuthService.init();
         };
    </script>
    

    And finally I have the action of the facebook button

    $(document).on("click", ".js-login-facebook", function () {
            $(".js-login-normal").attr("disabled", true);
            var l = Ladda.create(document.querySelector(".js-login-facebook"));
            l.start();
            fbAuthService.login('email,public_profile', function (response) {
                if (response.logged) {
                    var userService = new FacebookUserService();
                    userService.getUserInfo(response.uid, registerFbUser);
                    l.stop();
                }
            });
        });
    function registerFbUser(status, data) {
        if (status) {
            $.post(globalServerData.ajaxfbloginUrl, data, function (response) {
                bootbox.hideAll();
                console.log(response);
                if (response.status == true) {                    
                    return location.reload(true);
                }
                bootbox.alert(response.message);
            }, 'json');
    
        }
    }
    

    The situation is that I do not know where to start ... It is supposed that when one clicks the button the record is made in the data DB, followed by this the page is reloaded but it does not start automatically ... Then I have to click the button again to be able to login ... That's the process I follow ...

    Finally on the server side I have this that is part of facebook

     public function actionFacebookLogin() {
            /** @var Customer $customer */
            try {
                $guest = $this->getGuestActual();
                if ($guest->isCustomer()) {
                    throw new ValidationException('Ya tienes una session iniciada.');
                }
                $service = new FacebookUserService();
                $userInfo = $service->getUserInfo();
                $customer = Customer::find()->where(['fb_uid' => $userInfo->id])->one();
                if (empty($customer)) {
                    $customerService = new CustomerService();
                    $customer = $customerService->createByFacebook($userInfo);
                }
                $this->startCustomerSession($customer);
            } catch (ValidationException $e) {
                return json_encode(['status' => false, 'message' => $e->getMessage()]);
            } catch (\Exception $e) {
                return json_encode(['status' => false, 'message' => 'El usuario no existe.']);
            }
            return json_encode(['status' => true, 'message' => '']);
        }
    
        
    asked by cignius 29.10.2016 в 02:49
    source

    2 answers

    3
      

    The situation is that I do not know where to start ... It is supposed that when one clicks the button the record is made in the data DB, followed by this the page is reloaded but it does not start automatically ... Then I have to click the button again to be able to login ... That's the process I follow ...

    Let's recap what you have so far: When you click on the button, you end up invoking FB.login which, if necessary, opens a Facebook dialog where you can log in and / or authorize your page; up here all right, but then in the callback you invoke the function registerFbUser and this, in turn, makes the registration via Ajax and if everything goes well, it ends up invoking location.reload(true) . This reloads the page causing the FB module to lose the status of "logged in" .

    The solution provided by Facebook is to implement an automatic login when the page is loaded; The API already has this non-interactive login mechanism, which only makes the login if the user has already authorized the page and if it is currently logged in on Facebook. It is also valid both after completing the registration and when the user returns to visit your page another day, so it is logged automatically.

    The process is like this:

  • I'd rather invoke FB.init . Like this one, it seems to be fine.
  • Then invoke FB.getLoginStatus() to know if the user is already logged in to facebook and if your application is authorized. This is what causes the automatic login .
  • Then a quite simple solution would be that after invoking FB.init , invoke this other function. As FB.init is invoked inside the function FacebookAuthService.init we can put it there.

    It would be something like this:

    // esta es la funcion init de tu FacebookAuthService
    this.init = function () {
        FB.init({
            appId: config.fbappId,
            cookie: true,
            status: true,
            xfbml: config.fbxfbml,
            version: config.fbversion
        });
    
        // Ahora invocamos getLoginStatus
        FB.getLoginStatus(function(response) {
          if (response.status === 'connected') {
            // el usuario esta loggeado en facebook y ha autenticado
            // a tu web-app. Ademas, en respose.authReposnse se encuentra
            // el user ID y el Access token necesarios para luego invocar
            // las otras APIs (users y graph) 
    
            var uid = response.authResponse.userID;
            var accessToken = response.authResponse.accessToken;
    
          } else if (response.status === 'not_authorized') {
            // el usuario esta loggeado en facebook, pero no ha
            // atenticado tu aplicacion. 
    
          } else {
            // el usuario no esta logueado a facebook
          }
        });
    
        // por ultimo registrar el evento 
        FB.Event.subscribe('auth.authResponseChange', self.userStatusChange);
    };
    

    The truth is that it does not matter what code you put in the getLoginStatus callback because invoking it is what counts. However, look at the comments and you will see that the 3 states that return are very useful to determine how to continue, which buttons to enable, etc, etc.

    Salu2

        
    answered by 05.11.2016 / 06:09
    source
    -1

    Your main

    $(function() {
    
    var app_id = '000';//tu id app 
    var scopes = 'xxx, user_online_presence';//email
    
    var btn_login = '<a href="#" id="login" class="btn btn-primary">Iniciar sesión</a>';
    
    var div_session = "<div id='facebook-session'>"+
                      "<strong></strong>"+
                      "<img>"+
                      "<a href='#' id='logout' class='btn btn-danger'>Cerrar sesión</a>"+
                      "</div>";
    
    window.fbAsyncInit = function() {
    
        FB.init({
            appId      : app_id,
            status     : true,
            cookie     : true, 
            xfbml      : true, 
            version    : 'v2.1'
        });
    
    
        FB.getLoginStatus(function(response) {
            statusChangeCallback(response, function() {});
        });
    };
    
    var statusChangeCallback = function(response, callback) {
        console.log(response);
    
        if (response.status === 'connected') {
            getFacebookData();
        } else {
            callback(false);
        }
    }
    
    var checkLoginState = function(callback) {
        FB.getLoginStatus(function(response) {
            callback(response);
        });
    }
    
    var getFacebookData =  function() {
        FB.api('/me', function(response) {
            $('#login').after(div_session);
            $('#login').remove();
            $('#facebook-session strong').text("Bienvenido: "+response.name);
            $('#facebook-session img').attr('src','http://graph.facebook.com/'+response.id+'/picture?type=large');
        });
    }
    
    var facebookLogin = function() {
        checkLoginState(function(data) {
            if (data.status !== 'connected') {
                FB.login(function(response) {
                    if (response.status === 'connected')
                        getFacebookData();
                }, {scope: scopes});
            }
        })
    }
    
    var facebookLogout = function() {
        checkLoginState(function(data) {
            if (data.status === 'connected') {
                FB.logout(function(response) {
                    $('#facebook-session').before(btn_login);
                    $('#facebook-session').remove();
                })
            }
        })
    
    }
    
    
    
    $(document).on('click', '#login', function(e) {
        e.preventDefault();
    
        facebookLogin();
    })
    
    $(document).on('click', '#logout', function(e) {
        e.preventDefault();
    
        if (confirm("¿Está seguro?"))
            facebookLogout();
        else 
            return false;
    })
    
    })
    

    Your index

    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    
    
    <title>Facebook SDK para Javascript</title>
    
    <script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
    <script src="main.js"></script>
    
    <!-- Latest compiled and minified CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
    
    <!-- Optional theme -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css">
    

           

    Facebook SDK login with Javascript

        <a href="#" id="login" class="btn btn-primary">Iniciar sesión</a>
        <script>
        // Load the SDK asynchronously
          (function(d, s, id) {
            var js, fjs = d.getElementsByTagName(s)[0];
            if (d.getElementById(id)) return;
            js = d.createElement(s); js.id = id;
            js.src = "//connect.facebook.net/en_US/sdk.js";
            fjs.parentNode.insertBefore(js, fjs);
          }(document, 'script', 'facebook-jssdk'));
         </script>
    </body>
    </html>
    

    Try this, it seems to me that this version of Api is different from the one you have, so go to facebook developers and finish configuring the app

        
    answered by 01.11.2016 в 19:27