Jump to content

Social Sign In Module/Plugin using Hybridauth


dfunk006

Recommended Posts

  • 2 months later...

@Raymond Geerts - I ended up writing the login code in a template rather than a module (i figured it worked better that way). The code for integrating users is essentially taken from apeisa's Facebook Login Module - https://github.com/apeisa/FacebookLogin/blob/master/FacebookLogin.module

code for authenticating with hybridauth:

$hybridauth = new Hybrid_Auth( $ha_config );
  
$adapter = $hybridauth->authenticate( $provider_name );
  
$user_profile = $adapter->getUserProfile();

once you have successfully logged a user in with one of hybridauth's providers, you essentially need to call the processLogin function with the $user_profile object  (I've made some modifications but they may not be necessary):

Note: I have created a field - social_id and assigned it to users template. 

        $social_id = $user_profile->identifier;
        $display_name = $user_profile->displayName;

//you can capture additional information like email address, profile url, profile photo, etc from $user_profile object. see hybridauth for additional details.

        $name = $sanitizer->pageName($display_name, true).'-'.$social_id;
        $u = $this->users->get("social_id=$social_id");

        // First we create random pass to use in login
        $uniqid = uniqid();
        $pass = sha1($uniqid . $social_id . /*additional parameters can be added here*/);

        // User has logged in earlier with facebook id, great news let's login
        if ($u->id) {
            $u->of(false);
            $u->pass = $pass;
            /*$u->addRole(self::name);*/ //you can define a role for users
            $u->save();
        }

        else {
        
       // User has not logged in before and autogenerate is on //I'm not using this but feel free to use this if you like.

        /*else if (!$this->disableAutogenerate) {
            $name = $this->sanitizer->pageName($fbUserData->name, true);
            $u = $this->users->get("name=$name");

            // If there is already user account with same name than current logger has in facebook, then add a running number as a suffix //since i'm appending unique social ids in usernames, this problem will never arise

            if ($u->id) {
                if (!isset($fbUserData->counter)) {
                    $fbUserData->counter = 2;
                    $fbUserData->origName = $fbUserData->name;
                } else {
                    $fbUserData->counter++;
                }
                $fbUserData->name = $fbUserData->origName . $fbUserData->counter;
                $this->processLogin($fbUserData);
            } */

            // All seems to be fine, let's create the user // this is the main part

            $u = new User;
            $u->name = $name;
            $u->social_id = $social_id;
            $u->pass = $pass;
           /* $u->addRole(self::name);*/
            $u->addRole("member"); //i've added a role called member
            //you can create additional fields like email, profile url, etc and add them here.
            $u->save();
        }

        $this->session->login($name, $pass);
        $this->session->redirect(/*httpUrl*/);

My code is a bit different as per my requirements, but the above code should work for basic hybridauth authentication and integration with PW users.

Feel free to modify the code to suit your requirements.

Hope this helps.

Cheers! :)

  • Like 3
Link to comment
Share on other sites

  • 5 months later...

Hi All,

Wondered if anyone could provide me with some assistance with Hybridauth. I've installed the module, and just testing it with the following code.

$hybridauth = new Hybrid_Auth( $ha_config );
  
$adapter = $hybridauth->authenticate( $provider_name );
 

I get the following error. I have checked the pat and it does exist. 

Error: Exception: Hybriauth config does not exist on the given path. (in /var/www/web_new/site/modules/ProcessHybridAuth/hybridauth/Hybrid/Auth.php

thanks for any help

Link to comment
Share on other sites

Hybrid Auth will look for a path or array that you pass as $ha_config in to new Hybrid_Auth( $ha_config );

So if you have a config file somewhere assign its path to $ha_config before you assign an instance of the class.

Altough in the project i'm working on i'm passing an array with all the config values into it.

/**
 * Gets HybridAuth config data from module configuration settings
 *
 */
public function ___getHybridAuthConfig() {

    if ($this->page->template == "admin") return;

    if (in_array('active', $this->get('hybridauth'))) {
        $this->isHybridAuth = true;

        $this->hybridAuthConfig = array(
            'base_url' => $this->getHybridAuthBaseUrl(),
            'providers' => array(
                "AOL" => array(
                    "enabled" => $this->get('hybridauth_aol_status') == 'enabled' ? true : false
                ),
                "Facebook" => array(
                    "enabled" => $this->get('hybridauth_facebook_status') == 'enabled' ? true : false,
                    "keys" => array(
                        "id" => $this->get('hybridauth_facebook_app_id'),
                        "secret" => $this->get('hybridauth_facebook_app_secret')
                    ),
                    "trustForwarded" => in_array('trust_forwarded', $this->get('hybridauth_facebook_trust_forwarded')) ? true : false
                ),
                "Foursquare" => array(
                    "enabled" => $this->get('hybridauth_foursquare_status') == 'enabled' ? true : false,
                    "keys" => array(
                        "id" => $this->get('hybridauth_foursquare_app_id'),
                        "secret" => $this->get('hybridauth_foursquare_app_secret')
                    )
                ),
                "Google" => array(
                    "enabled" => $this->get('hybridauth_google_status') == 'enabled' ? true : false,
                    "keys" => array(
                        "id" => $this->get('hybridauth_google_app_id'),
                        "secret" => $this->get('hybridauth_google_app_secret')
                    )
                ),
                "LinkedIn" => array(
                    "enabled" => $this->get('hybridauth_linkedin_status') == 'enabled' ? true : false,
                    "keys" => array(
                        "key" => $this->get('hybridauth_linkedin_app_id'),
                        "secret" => $this->get('hybridauth_linkedin_app_secret')
                    )
                ),
                "OpenID" => array(
                    "enabled" => $this->get('hybridauth_openid_status') == 'enabled' ? true : false
                ),
                "Twitter" => array(
                    "enabled" => $this->get('hybridauth_twitter_status') == 'enabled' ? true : false,
                    "keys" => array(
                        "key" => $this->get('hybridauth_twitter_app_id'),
                        "secret" => $this->get('hybridauth_twitter_app_secret')
                    )
                ),
                // Windows Live
                "Live" => array(
                    "enabled" => $this->get('hybridauth_windowslive_status') == 'enabled' ? true : false,
                    "keys" => array(
                        "id" => $this->get('hybridauth_windowslive_app_id'),
                        "secret" => $this->get('hybridauth_windowslive_app_secret')
                    )
                ),
                "Yahoo" => array(
                    "enabled" => $this->get('hybridauth_yahoo_status') == 'enabled' ? true : false,
                    "keys" => array(
                        "key" => $this->get('hybridauth_yahoo_app_id'),
                        "secret" => $this->get('hybridauth_yahoo_app_secret')
                    )
                )
            ),
            // If you want to enable logging, set 'debug_mode' to true.
            // You can also set it to
            // - "error" To log only error messages. Useful in production
            // - "info" To log info and error messages (ignore debug messages)
            "debug_mode" => "",
            // Path to file writable by the web server. Required if 'debug_mode' is not false
            "debug_file" => $this->config->paths->logs . "hybridauth.txt",
        );
    }
}
  • Like 3
Link to comment
Share on other sites

Getting stuck with BASE_URL now.

What do you add as your "base_url" => "http://site_namesite/modules/ProcessHybridAuth/hybridauth/",

You could make a template that initializes the Hybrid Auth class, assign it to a page and use that as endpoint URL.

For example:

/**
 * Provides HybridAuth actions
 *
 */
public function ___actionHybridAuth() {

    if (!$this->isHybridAuth) return;

    if ($this->page !== self::$fup['hybridauth']) return;

    if ($this->sanitizer->name($this->input->urlSegment1)) {

        $this->initializeHybridAuth();

    } else $this->endpointHybridAuth();
}

/**
 * Initializes HybridAuth endpoint
 *
 */
public function ___endpointHybridAuth() {

    if (!$this->isHybridAuth) return;

    if ($this->page !== self::$fup['hybridauth']) return;

    @require_once (dirname(__FILE__) . '/Hybrid/Auth.php');
    @require_once (dirname(__FILE__) . '/Hybrid/Endpoint.php');
    Hybrid_Endpoint::process();
}

(note: above example is part of a module i'm working on, the code is just for illustrating a way of using hybridauth class inside a module, the code itself wont do much without the rest of the module)

Edited by Raymond Geerts
  • Like 1
Link to comment
Share on other sites

thanks Raymond and sorry for being so needy, I'm such a newbie.  The code you provided gives me the following error.

Parse Error: syntax error, unexpected T_PUBLIC (line 6 of /var/www/www.bommachine.co.uk/site/templates/hybrid.php) 

Line 6

public function ___actionHybridAuth() {
Link to comment
Share on other sites

I wouldnt recommend using my code as it was merely to demonstrate how i did it inside a module. SInce the module isnt standalone and still in development its no use to give the full code.

Besides that using a scope (like public, private, protected) for a function/methods can only be used inside a class. When you define a function outside a class leave away the scope.

function actionHybridAuth() {
    // rest of the code
}

But again using my code without the rest of the modules that belong with it will not work. Sorry i cant be much of a help there.

Anyway i would recommend to read some into using classes, methods and such, since the HybridAuth is a class by itself. Implementing it in to your ProcessWire project will require some basic understanding of how to use PHP classes and methods.

  • Like 1
Link to comment
Share on other sites

  • 1 year later...
  • 1 year later...

@dfunk006Please help me with the problem you used to have.

Fatal error: Uncaught exception 'Hybrid_Exception' with message 'You cannot access this page directly.' in /usr/local/www/web.local/cases/site/libraries/hybridauth/hybridauth/Hybrid/Endpoint.php

I changed the session name to PHPSESSID as you suggested but unfortunately it didn't help me.

Huge Thanks in advance.

Link to comment
Share on other sites

hey @DedMoroz,

That was a long time ago and I'm not quite sure I remember the details but let me try. Where have you placed your Hybridauth folder?

If you put Hybridauth in the site/ directory, it will use the default PHP session.save_path. Your template in Processwire uses pw's session path (assets/sessions). You need to ensure that both the session paths are same for it to work.

You can do this by commenting the following line in index.php

//if(ini_get('session.save_handler') == 'files') ini_set("session.save_path", rtrim($config->paths->sessions, '/')); 

This will make pw's session.save_path as the default PHP session.save_path. Now session variables can easily be passes between PW and Hybridauth templates.

 

  • Like 1
Link to comment
Share on other sites

@dfunk006

Thank you for the quick respond!


I placed Hybridauth in site/libraries/hybridauth

Probable we are talking about different versions of PW (mine - 3), because I didn't find that piece of code in index.php. 

But I found and comment this in Session.php

		if(ini_get('session.save_handler') == 'files') {
			if(ini_get('session.gc_probability') == 0) {
				// Some debian distros replace PHP's gc without fully implementing it,
				// which results in broken garbage collection if the save_path is set.
				// As a result, we avoid setting the save_path when this is detected.
			} else {
				ini_set("session.save_path", rtrim($this->config->paths->sessions, '/'));
			}
		}

And it doesn't help.

Any other suggestions?

Thanks a lot!

Edited by DedMoroz
Link to comment
Share on other sites

  • 1 month later...
  • 5 months later...
  • 4 years later...
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...