Login with Google Plus OAuth in CakePHP
In this tutorial we are going to see how to integrate Google Plus OAuth Login using CakePHP. I had already implemented Google OAuth Login Using PHP in one of my previous tutorial. Please refer that tutorials before continuing this further.
Here is that tutorials.
Create Google Application Or Project:
In Google OAuth Login Integration first and foremost thing we need to is to create Google Apps to get Google Oauth Client ID and Client Secret. I had briefly explained creation of Google apps on the Google Login using PHP Tutorial. So please follow the step 1 of this tutorial to create Google Apps . Here is the Link…
Once you completed Step 1 of the above tutorial successfully, then you will get Google Oauth Client ID and Client Secret to integrate Google Oauth login in your CakePHP webapplication.
Crate Sample Table For Google OAuth Login Using CakePHP
Create following sample users table in your Database for this cakephp login with google.
CREATE TABLE IF NOT EXISTS `users` ( `id` int(11) NOT NULL AUTO_INCREMENT, `first_name` varchar(60) DEFAULT NULL, `last_name` varchar(60) DEFAULT NULL, `email` varchar(80) DEFAULT NULL, `password` varchar(64) DEFAULT NULL, `social_id` varchar(45) DEFAULT NULL, `picture` varchar(100) DEFAULT NULL, `gender` char(1) DEFAULT NULL, `created` datetime DEFAULT NULL, `updated` datetime DEFAULT NULL, `uuid` varchar(70) DEFAULT NULL, `status` int(11) DEFAULT NULL, PRIMARY KEY (`id`), KEY `email_idx` (`email`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
Google OAuth Login Integration In CakePHP:
To integrate Google OAuth Login in your CakePHP Webapplications, we need Google API PHP Script to make OAuth request to Google. I have downloaded recent version Google API PHP Script from Github from the following link.
Note : It’s best advisable to use Google API PHP Script i had used in this tutorial to successfully integrate Google login in your CakePHP webapplication. Please download source file using above download link.
Now I have created a folder name Google in the app/Vendor directory, then from downloaded Google api php script copied only src directory and pasted it in the app/Vendor/Google directory. Now it is app/Vendor/Google/src..
Include Google API PHP Script In Your CakePHP Application:
Create site_config.php file in the app/Config directory to keep all your application wide constants. Here is my site_config.php file. Where please replace your client id and client secret.
<?php require_once 'messages.php'; //db config define('DB_HOST', 'localhost'); define('DB_NAME', 'cake_login'); define('DB_USER', 'root'); define('DB_PASS', ''); define('DB_PREFIX', ''); //site config define('BASE_PATH', 'http://localhost/cakelogin/'); //Google App Details define('GOOGLE_APP_NAME', 'Smart Quiz'); define('GOOGLE_OAUTH_CLIENT_ID', 'YOUR CLIENT_ID'); define('GOOGLE_OAUTH_CLIENT_SECRET', 'YOUR CLIENT_SECRET'); define('GOOGLE_OAUTH_REDIRECT_URI', 'http://localhost/cakelogin/google_login'); define("GOOGLE_SITE_NAME", 'http://localhost/');
Please include this site_config.php file in your bootstrap.php file in the app/Config directory.
Before we are going to make any OAuth API request to Google we must include that Google PHP API script in our file. For that I am creating google_login.php file in the app/Config directory and including following files. Here is my google_login.php file.
<?php /*******Google ******/ require_once '../Vendor/Google/src/config.php'; require_once '../Vendor/Google/src/Google_Client.php'; require_once '../Vendor/Google/src/contrib/Google_PlusService.php'; require_once '../Vendor/Google/src/contrib/Google_Oauth2Service.php';
Making Google Oauth API Request:
To make Google OAuth API request and to handle Google OAuth response I am creating following two functions. where googlelogin() function which makes Google OAuth login request, and google_login() function which handles Google OAuth login response from the Google.
This following two functions I had kept it in UsersController.php file. So here is the my CakePHP scripts of the two functions.
/** * This function will makes Oauth Api reqest */ public function googlelogin() { $this->autoRender = false; require_once '../Config/google_login.php'; $client = new Google_Client(); $client->setScopes(array('https://www.googleapis.com/auth/plus.login','https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/plus.me')); $client->setApprovalPrompt('auto'); $url = $client->createAuthUrl(); $this->redirect($url); } /** * This function will handle Oauth Api response */ public function google_login() { $this->autoRender = false; require_once '../Config/google_login.php'; $client = new Google_Client(); $client->setScopes(array('https://www.googleapis.com/auth/plus.login','https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/plus.me')); $client->setApprovalPrompt('auto'); $plus = new Google_PlusService($client); $oauth2 = new Google_Oauth2Service($client); if(isset($_GET['code'])) { $client->authenticate(); // Authenticate $_SESSION['access_token'] = $client->getAccessToken(); // get the access token here } if(isset($_SESSION['access_token'])) { $client->setAccessToken($_SESSION['access_token']); } if ($client->getAccessToken()) { $_SESSION['access_token'] = $client->getAccessToken(); $user = $oauth2->userinfo->get(); try { if(!empty($user)){ $result = $this->User->findByEmail( $user['email'] ); if(!empty( $result )){ if($this->Auth->login($result['User'])){ $this->Session->setFlash(GOOGLE_LOGIN_SUCCESS, 'default', array( 'class' => 'message success'), 'success' ); $this->redirect(BASE_PATH); }else{ $this->Session->setFlash(GOOGLE_LOGIN_FAILURE, 'default', array( 'class' => 'message error'), 'error' ); $this->redirect(BASE_PATH.'login'); } }else{ $data = array(); $data['email'] = $user['email']; $data['first_name'] = $user['given_name']; $data['last_name'] = $user['family_name']; $data['social_id'] = $user['id']; $data['picture'] = $user['picture']; $data['gender'] = $user['gender'] == 'male' ? 'm':'f'; $data['user_level_id'] = 1; $data['uuid'] = String::uuid(); $this->User->save( $data ); if($this->User->save( $data )){ $data['id'] = $this->User->getLastInsertID(); if($this->Auth->login($data)){ $this->Session->setFlash(GOOGLE_LOGIN_SUCCESS, 'default', array( 'class' => 'message success'), 'success' ); $this->redirect(BASE_PATH); }else{ $this->Session->setFlash(GOOGLE_LOGIN_FAILURE, 'default', array( 'class' => 'message error'), 'error' ); $this->redirect(BASE_PATH.'login'); } }else{ $this->Session->setFlash(GOOGLE_LOGIN_FAILURE, 'default', array( 'class' => 'message error'), 'error' ); $this->redirect(BASE_PATH.'login'); } } }else{ $this->Session->setFlash(GOOGLE_LOGIN_FAILURE, 'default', array( 'class' => 'message error'), 'error' ); $this->redirect(BASE_PATH.'login'); } }catch (Exception $e) { $this->Session->setFlash(GOOGLE_LOGIN_FAILURE, 'default', array( 'class' => 'message error'), 'error' ); $this->redirect(BASE_PATH.'login'); } } exit; }
Google Oauth Login Link:
Finally we need to give Google OAuth login link to user to use google login. Here is my html markup.
<a class="btn btn-default google" href="<?php echo BASE_PATH.'googlelogin'; ?>"> <i class="fa fa-google-plus modal-icons"></i> Signin with Google </a>
CakePHP Routing for Google Login:
I had modified url string for our Google login to look nice. So please add the following lines of code in your routes.php file in the app/Config directory.
Router::connect('/googlelogin', array('controller' => 'users', 'action' => 'googlelogin')); Router::connect('/google_login', array('controller' => 'users', 'action' => 'google_login'));
CakePHP Auth Allow() for Google Login:
Final thing we need to allow user to access following two functions googlelogin() and google_login() without logging in our system in the beforeFilter() of UsersController.
public function beforeFilter() { $this->Auth->allow('google_login', 'googlelogin' ); parent::beforeFilter(); }
You may also like some of my tutorial on CakePHP
Download Premium Only Scripts & 80+ Demo scripts Instantly at just 1.95 USD per month + 10% discount to all Exclusive Scripts
If you want any of my script need to be customized according to your business requirement,
Please feel free to contact me [at] muni2explore[at]gmail.com
Note: But it will be charged based on your customization requirement