10/02/2017 1:15am

PHP | Working Example -


<?php


/**
* Authenticate with SilverStripe via Google, Facebook, Twitter using the hybridauth
*/
class LoginPage extends Page {

}

class LoginPage_Controller extends Page_Controller {

private static $allowed_actions = array(
'hybridauth',
'facebook',
'google',
'twitter'
);

public function facebook() {
require_once( FRAMEWORK_PATH . "/../vendor/hybridauth/hybridauth/hybridauth/Hybrid/Auth.php" );

$facebookkeys = Config::inst()->get('LoginPage', 'facebookconfig');

$facebookkeys['keys'] = $facebookkeys['keys'][Director::get_environment_type()];

$config = array(
"base_url" => $this->join_links(Director::absoluteURL($this->Link()), "hybridauth"),
"providers" => array(
"Facebook" => $facebookkeys
)
);

try {
$hybridauth = new Hybrid_Auth($config);
$adapter = $hybridauth->authenticate("Facebook");
$user_profile = $adapter->getUserProfile();
} catch (Exception $e) {
throw new SS_HTTPResponse_Exception("Error: " . $e->getMessage());
}

// Here you create your user. You could also match/ create a member object.
$learner = MyOauthUser::create();

$learner->FirstName = $user_profile->firstName;
$learner->Email = $user_profile->email;
$learner->LastName = $user_profile->lastName;
$learner->Identifier = $user_profile->identifier;
$learner->ProfileData = var_export((array) $user_profile, true);

$learner->write();

// redirect here
}

/**
* Handles the authentication via the hybridauth module
*/
public function hybridauth() {
require_once( FRAMEWORK_PATH . "/../vendor/facebook/graph-sdk/src/Facebook/Facebook.php" );
require_once( FRAMEWORK_PATH . "/../vendor/hybridauth/hybridauth/hybridauth/index.php" );
}

}


auth.yml:

---
LoginPage:
facebookconfig:
enabled: true
keys:
live:
id: <live app here>
secret: <live secret here>
test:
dev:
id: <dev app id here>
secret: <dev secret here>
scope:
- email
- user_about_me
- user_birthday
- user_hometown
display: popup



This example demonstrates how to use the hybridauth module with SilverStripe, installed via composer.

The composer version by default installs into the /vendor folder, which by default is blocked by nginx and apache configuration. Also there is a bug in the composer version which fails to auto load the facebook (and presumably the Twitter and Google) libraries.

This example shows how to get facebook working (with stubs for twitter and google).

The YML file shows how to create a config for the library.

You can authenticate by navigating to /yourloginpage/facebook

Tags : hybridauth authentication