How to Create Social login in CakePHP With HybridAuth Library

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.

Let’s create something beautiful and innovative together! call us now!

Chat with our seniors to see if we have a good match

SHARE IT ON

Comments

9 responses to “How to Create Social login in CakePHP With HybridAuth Library”
  1. Hi, very good article
    Thanks for sharing keep up the work

    1. Thank you, Trisha.

  2. kinder810 Avatar

    amazing article thanks for sharing this important information

  3. Dr. vivek saini Avatar

    it’s such a nice and very useful article. Thanks for sharing,Thanks for this Wonderful article.

  4. Dr. vivek saini Avatar

    It is Very nice and Helpful Article. Thank you for sharing, Thanks again.

    1. You’re most welcome, Keep subscribe us to get more info about development and more.

  5. Sukanta Das Avatar

    It is very useful article for me, thanks

    1. It’s my pleasure, Sukanta Das, that you find it helpful.

  6. karmveer Avatar

    Call to undefined method ADmad\HybridAuth\Controller\HybridAuthController::newEntity()
    how to solve

Leave a Reply

Your email address will not be published. Required fields are marked *

BLOG

Our recent post