PHP

How to Create Social login in CakePHP With HybridAuth Library

Author By Chandan Kumar
July 21, 2017
8 min read
Share:
CakePHP

Today I am writing about new steps to create a social login in CakePHP with HybridAuth library, what exactly you required for social media integration, and the steps you can find below and go through the post step and complete your CakePHP HybridAuth development study.

A CakePHP plugin which allows using the HybridAuth social sign on library

CakePHP HybridAuth

Required:

  • CakePHP 3.x. If not then click here to see the installation steps.

  • Users login

HybridAuth

Installation:

Run this command:

[code]

<em>$ composer require --prefer-dest admad/cakephp-hybridauth</em>[/code]

Setup:

Run this command:

[code]
$ bin/cake plugin load ADmad/HybridAuth -b -r[/code]

Configuration:

Create a file “hybridauth.php” inside of config folder:

config/hybridauth.php:

Create Social login in CakePHP with HybridAuth Library
[code]

use Cake\Core\Configure;

return [

'HybridAuth' => [

'providers' => [

'Google' => [

'enabled' => true,

'keys' => [

'id' => '<google-client-id>',

'secret' => '<secret-key>'

],

"scope" => 'https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/plus.profile.emails.read',// optional

"approval_prompt" => "force"

],

'Facebook' => [

'enabled' => true,

'keys' => [

'id' => '<facebook-application-id>',

'secret' => '<secret-key>'

],

'scope' => 'email, user_about_me, user_hometown'

],

'LinkedIn' => [

'enabled' => true,

'keys' => [

'id' => '<linkedin-key>',

'secret' => '<secret-key>'

],

"scope"   => "r_basicprofile r_emailaddress", // optional

]

],

'debug_mode' => Configure::read('debug'),

'debug_file' => LOGS . 'hybridauth.log',

]

];
[/code]

Database:

Create a table “social_profiles” run below command:

[code]$ bin/cake migrations migrate -p ADmad/HybridAuth[/code]

Usage:

In AppController’s initialize() method add below script for allowing social login:

Create Social login in CakePHP with HybridAuth Library

# FOR ALLOWING FACEBOOK LOGIN ALSO

[code]

parent::initialize();

$this->loadComponent('Auth', [

'authenticate' => [

'Form',

'ADmad/HybridAuth.HybridAuth' => [

// All keys shown below are defaults

'fields' => [

'provider' => 'provider',

'openid_identifier' => 'openid_identifier',

'email' => 'email'

],[/code]
[code]

'profileModel' => 'ADmad/HybridAuth.SocialProfiles',

'profileModelFkField' => 'user_id',

'userModel' => 'Users',[/code]
[code]
// The URL Hybridauth lib should redirect to after authentication.

// If no value is specified you are redirect to this plugin's

// HybridAuthController::authenticated() which handles persisting

// user info to AuthComponent and redirection.

'hauth_return_to' => [

'controller'  => 'Venues',

'action'      => 'update_status',

'plugin' => false

]

]

],

'loginRedirect' => array('controller' => '<controller Name>', 'action' => '<Method name>'),

'logoutRedirect' => array('controller' => '<controller Name>', 'action' => '<Method name'),

]);[/code]

Your UserController’s login method should be similar to this:

Create Social login in CakePHP with HybridAuth Library
[code]public function login() {

if ($this->request->is('post') || $this->request->query('provider')) {

$user = $this->Auth->identify();

if ($user) {

$this->Auth->setUser($user);

return $this->redirect($this->Auth->redirectUrl());

}

$this->Flash->error(__('Invalid username or password, try again'));

}

}

[/code]

On your login page, you can create links to initiate authentication using required providers. Specify the provider name using the variable named provider in the query string.

[code]echo $this->Form->postLink(

'Login with Google',

['controller' => 'Users', 'action' => 'login', '?' => ['provider' => 'Google']]

);

[/code]

Setup a method of your UsersTable as a callback for the event:

Create Social login in CakePHP with HybridAuth Library
[code]

public function initialize(array $config)

{

parent::initialize($config);

[/code]
[code]

$this->setTable('users');

$this->setDisplayField('id');

$this->setPrimaryKey('id');

$this->addBehavior('Timestamp');

$this->hasMany('ADmad/HybridAuth.SocialProfiles');

\Cake\Event\EventManager::instance()->on('HybridAuth.newUser', [$this, 'createUser']);

}

[/code]

public function createUser(\Cake\Event\Event $event)

[code] {

// Entity representing record in social_profiles table

$profile = $event->data()['profile'];

[/code]

// Make sure here that all the required fields are actually present

[code]
$user = $this->newEntity(['email' => $profile->email]);

$user = $this->save($user);

[/code]

if (!$user) {

throw new \RuntimeException(‘Unable to save new user’);

}

[code]

return $user;

}

[/code]

Create a Model src/Model/SocialProfilesTable.php and add similar to this:

Create Social login in CakePHP with HybridAuth Library
[code]

namespace ADmad\HybridAuth\Model\Table;

use Cake\ORM\Table;

/**

* HybridAuth Authenticate

*

* Licensed under The MIT License

* For full copyright and license information, please see the LICENSE.txt

*/

class SocialProfilesTable extends Table

{

/**

* Initialize table.

*

* @param array $config Configuration

* @return void

*/

public function initialize(array $config)

{

parent::initialize($config);

$this->addBehavior('Timestamp');

$this->belongsTo('Users');

}

}

[/code]
For more information about the CakePHP Hybridauth, configuration array clicks here. I hope you will find the article informative about CakePHP HybridAuth Library, If you find any problem fixing it, please contact us and help you out. Also, share your thoughts below in the comment box about CakePHP HybridAuth Library.

Chandan Kumar

Chandan Kumar

Related Articles

Continue reading with these hand-picked articles on similar topics.

PHP: How To Parse Decimal Number from String
PHP
PHP: How To Parse Decimal Number from String
$string = "$4.9/inch"; $res = filter_var($string, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION); echo $res; It will print4.9
Chandan Kumar May 1, 2020