How to Create Social login in CakePHP With HybridAuth Library

Today I am writing about new steps that how to create a social login in CakePHP with HybridAuth library, what exactly you required for social media integration and what the steps, you can find below and go through the post step by 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:


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

 

Setup:

Run this command:

$ bin/cake plugin load ADmad/HybridAuth -b -r

Configuration:

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

config/hybridauth.php:

CakePHP HybridAuth - Avyatech


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',

]

];

 

Database:

Create a table “social_profiles” run below command:

$ bin/cake migrations migrate -p ADmad/HybridAuth

 

Usage:

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

CakePHP HybridAuth - Avyatech 2

# FOR ALLOWING FACEBOOK LOGIN ALSO


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'

],

 


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

'profileModelFkField' => 'user_id',

'userModel' => 'Users',

 

// 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'),

]);

 

 

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

CakePHP HybridAuth - Avyatech 3
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'));

}

}

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.

echo $this->Form->postLink(

'Login with Google',

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

);

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

CakePHP HybridAuth - Avyatech 4

public function initialize(array $config)

{

parent::initialize($config);


$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']);

}

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

 {

// Entity representing record in social_profiles table

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

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

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

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

if (!$user) {

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

}


return $user;

}

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

CakePHP HybridAuth - Avyatech 5


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');

}

}

For more information about the CakePHP hybridauth configuration array click here.

 

I hope you will find the article informative about CakePHP HybridAuth Library, If you find any problem to fix it then plz contact us and will help you out. Also, share your thoughts below in the comment box about CakePHP HybridAuth Library.
More Informative Write Ups
Avyatech Logo