Search code examples
javascriptphpjqueryajaxhybridauth

HybridAuth not working with ajax


I'm trying to implement HybridAuth with ajax.

Code:

PHP: (will be called by ajax)

<?php
header('Content-type: application/json');
$provider = $_GET["provider"];
$config = '../libaries/hybridauth/config.php';
require_once( "../libaries/hybridauth/Hybrid/Auth.php" );
try {
    $hybridAuth = new Hybrid_Auth($config);

    $adapter = $hybridAuth->authenticate($provider);    
    $userProfile = json_encode($adapter->getUserProfile());
    echo $_GET['callback'] . '(' . "{$userProfile}" . ')';
} catch (Exception $e) {
    echo "Ooophs, we got an error: " . $e;
}
?>

Javascript:

socialRegister: function () {
    var self = this;
    var val = 'provider=' + self.get("provider");
    return $.ajax({
        type: "GET",
        url: path.urlRoot + 'ext/socialRegisterAndAuthentication.inc.php',
        dataType: "jsonp",
        data: val
    });
}

But I always get following error:

XMLHttpRequest cannot load https://api.twitter.com/oauth/authenticate?oauth_token=123. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access.

I know, that this means, that the Twitter Server is not allowing my origin. Is there a workaround? Is a "One-Page" signUp with ajax possible? (Hopefully yes - on quora.com it works ;) )

TWITTERSETTINGS: enter image description here

Best Fabian


Solution

  • First of all - HybridAuth and ajax directly is not working. But i have a satisfying solution now and i want to share it with you. So here is how i did it:

    JavaScript:

    twitterRegister: function () {
                var self = this;
                self.popupWindow = window.socialPopupWindow = window.open(
                        path.urlRoot + 'ext/socialRegisterAndAUthentication.inc.php?provider=Twitter',
                        "hybridauth_social_sing_on",
                        "location=0,status=0,scrollbars=0,width=800,height=500"
                        );
                var winTimer = setInterval(function ()
                {
                    if (self.popupWindow.closed !== false)
                    {
                        // !== is required for compatibility with Opera
                        clearInterval(winTimer);
    
                        //Now twitter register from
                        require(["model/register"], function (registerModel) {
                            var registerM = new registerModel();                      
                            var ajaxRequest = registerM.socialRegister();
                            $.when(ajaxRequest).done(function (response) {
                                console.log(response);
                                self.slideOutRegister("Twitter");
                                self.twitterObject = response;
                                $('#reg_user').val(response.firstName);
                            });
                            $.when(ajaxRequest).fail(function () {
                                self.slideOutRegister("Email");
                            });
                        });
                    }
                }, 200);
    
            },
    

    Explanation: This function opens a new popup-window. The user will be prompted to authorize the app. The setInterval catches the close event (fired by the window itself when its done).

    socialRegisterAndAUthentication.inc.php:

    <?php
    
    session_start();
    header('Content-type: text/html');
    $provider = $_GET["provider"];
    $config = '../libaries/hybridauth/config.php';
    require_once( "../libaries/hybridauth/Hybrid/Auth.php" );
    try {
        $hybridAuth = new Hybrid_Auth($config);
        $adapter = $hybridAuth->authenticate($provider);
        $_SESSION["userProfile"] = json_encode($adapter->getUserProfile());
        echo "<script type='text/javascript'>";
        echo "window.close();";
        echo "</script>";
    } catch (Exception $e) {
        echo "Ooophs, we got an error: ";
    }
    ?>
    

    Explanation: Closes the window when authorization is done (this is from the docs of HybridAuth). The data is stored in a session so that i can retrieve it later per ajax.

    getSocialData.inc.php

    <?php
    session_start();
    header('Content-type: application/json');
    echo $_GET['callback'] . '(' . "{$_SESSION["userProfile"]}" . ')';
    ?>
    

    Explanation: Returns the stored userProfile.

    Summary:

    Open a popup-window with javascript and let the user authorize the app. Store the data in a Session variable. Catch the close event of the popup-window. Then make an ajax call to retrieve the stored data (Session).