Google OAuth API is the easiest option to integrate login system in the website. Google OAuth login system helps the user to login to the web application using their Google plus account. The main advantages of Google login are the user can login to the web application with their existing Google account without register on the website.
Google OAuth Login can be integrated into the website using PHP and JavaScript. In this tutorial, we will learn how to integrate Login with Google account in CodeIgniter using Google API PHP Client Library. The example script allows you can implement Login with Google account in CodeIgniter application and store the Google+ profile information in the MySQL database.
Before you begin to integrate Login with Google in CodeIgniter, take look at the folders and files structure.
-
codeigniter/
-
application/
-
config/
- google.php
-
controllers/
- User_authentication.php
-
libraries/
- Google.php
-
models/
- User.php
-
third_party/
- google-api-client/
-
views/
-
user_authentication/
- index.php
- profile.php
-
user_authentication/
-
config/
-
assets/
- images
-
application/
Google Project Creation
To use Google API Client Library, you need to create a Google API project in the Google API Console. You should need to specify Authorized redirect URIs that will be the same of user authentication controller URL (http://localhost/codeigniter/user_authentication/). After project creation, the Client ID and Client secret will be generated in Google API project console.
Go through this step-by-step guide to create Google API Console Project – How to Create Google Developers Console Project
Once your Google API project creation is completed, copy the Client ID and Client secret and put them into the respective variable in the script (Google API Configuration file).
Create Database Table
To store the user profile information, you need to create a table into the database. The following SQL creates a users
table in the MySQL database for inserting the Google+ profile information.
CREATE TABLE `users` ( `id` int(11) NOT NULL AUTO_INCREMENT, `oauth_provider` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `oauth_uid` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `first_name` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `last_name` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `email` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `gender` varchar(10) COLLATE utf8_unicode_ci NOT NULL, `locale` varchar(10) COLLATE utf8_unicode_ci NOT NULL, `picture_url` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `profile_url` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `created` datetime NOT NULL, `modified` datetime NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
Config (application/config/)
autoload.php
Some libraries and helper are needed for Google login, it’s a better idea to specify these once in the autoload.php file.
Load the session and database libraries:
$autoload['libraries'] = array('session','database');
Load the URL helper:
$autoload['helper'] = array('url');
google.php
Google API configuration variables are defined in this file. You need to specify the Client ID, Client secret and Redirect URI according to your Google API Console Project credentials.
<?php defined('BASEPATH') OR exit('No direct script access allowed');
/*
| -------------------------------------------------------------------
| Google API Configuration
| -------------------------------------------------------------------
| client_id string Your Google API Client ID.
| client_secret string Your Google API Client secret.
| redirect_uri string URL to redirect back to after login.
| application_name string Your Google application name.
| api_key string Developer key.
| scopes string Specify scopes
*/
$config['google']['client_id'] = 'Google_API_Client_ID';
$config['google']['client_secret'] = 'Google_API_Client_Secret';
$config['google']['redirect_uri'] = 'http://localhost/codeigniter/user_authentication/';
$config['google']['application_name'] = 'Login to solutiondoodz.blogspot.com';
$config['google']['api_key'] = '';
$config['google']['scopes'] = array();
Google API PHP Client Library (application/third_party/)
Google API PHP client is used to connect with Google OAuth API, place the google-api-client
library in the third_party/
directory of CodeIgniter application.
Note that: You will get the Google API client library files in our source code.
Google OAuth Library (application/libraries/)
The Google class helps to integrate Google API client in CodeIgniter 3.x application. You can easily add the Login with Google functionality using PHP API client and Google library.
<?php defined('BASEPATH') OR exit('No direct script access allowed');
/**
* Google OAuth Library for CodeIgniter 3.x
*
* Library for Google+ login. It helps the user to login with their Google account
* in CodeIgniter application.
*
* This library requires the Google API PHP client and it should be placed in third_party folder.
*
* It also requires google configuration file and it should be placed in the config directory.
*
* @package CodeIgniter
* @category Libraries
* @author solutiondoodz
* @link https://solutiondoodz.blogspot.com/
* @version 2.0
*/
class Google{
public function __construct(){
$CI =& get_instance();
$CI->config->load('google');
require APPPATH .'third_party/google-api-client/Google_Client.php';
require APPPATH .'third_party/google-api-client/contrib/Google_Oauth2Service.php';
$this->client = new Google_Client();
$this->client->setApplicationName($CI->config->item('application_name', 'google'));
$this->client->setClientId($CI->config->item('client_id', 'google'));
$this->client->setClientSecret($CI->config->item('client_secret', 'google'));
$this->client->setRedirectUri($CI->config->item('redirect_uri', 'google'));
$this->client->setDeveloperKey($CI->config->item('api_key', 'google'));
$this->client->setScopes($CI->config->item('scopes', 'google'));
$this->client->setAccessType('online');
$this->client->setApprovalPrompt('auto');
$this->oauth2 = new Google_Oauth2Service($this->client);
}
public function loginURL() {
return $this->client->createAuthUrl();
}
public function getAuthenticate() {
return $this->client->authenticate();
}
public function getAccessToken() {
return $this->client->getAccessToken();
}
public function setAccessToken() {
return $this->client->setAccessToken();
}
public function revokeToken() {
return $this->client->revokeToken();
}
public function getUserInfo() {
return $this->oauth2->userinfo->get();
}
}
Controller (application/controllers/User_authentication.php)
The User_Authentication controller contains four functions, __construct()
, index()
, profile()
, and logout()
.
- __construct() – The Google library and User model are loaded in this method.
-
index() – The following functionalities are implemented in this method.
- Connects with Google OAuth API using the Google library, authenticate, and fetch the Google plus profile information.
- Pass the user profile information to the User model to insert into the database.
- Loads the login view for the non-authenticated user.
- profile() – Retrieve the user data from session and load the profile view to display the user’s profile info.
- logout() – Removes the user data from session and log out the user from their Google account.
<?php defined('BASEPATH') OR exit('No direct script access allowed');
class User_Authentication extends CI_Controller
{
function __construct(){
parent::__construct();
//load google login library
$this->load->library('google');
//load user model
$this->load->model('user');
}
public function index(){
//redirect to profile page if user already logged in
if($this->session->userdata('loggedIn') == true){
redirect('user_authentication/profile/');
}
if(isset($_GET['code'])){
//authenticate user
$this->google->getAuthenticate();
//get user info from google
$gpInfo = $this->google->getUserInfo();
//preparing data for database insertion
$userData['oauth_provider'] = 'google';
$userData['oauth_uid'] = $gpInfo['id'];
$userData['first_name'] = $gpInfo['given_name'];
$userData['last_name'] = $gpInfo['family_name'];
$userData['email'] = $gpInfo['email'];
$userData['gender'] = !empty($gpInfo['gender'])?$gpInfo['gender']:'';
$userData['locale'] = !empty($gpInfo['locale'])?$gpInfo['locale']:'';
$userData['profile_url'] = !empty($gpInfo['link'])?$gpInfo['link']:'';
$userData['picture_url'] = !empty($gpInfo['picture'])?$gpInfo['picture']:'';
//insert or update user data to the database
$userID = $this->user->checkUser($userData);
//store status & user info in session
$this->session->set_userdata('loggedIn', true);
$this->session->set_userdata('userData', $userData);
//redirect to profile page
redirect('user_authentication/profile/');
}
//google login url
$data['loginURL'] = $this->google->loginURL();
//load google login view
$this->load->view('user_authentication/index',$data);
}
public function profile(){
//redirect to login page if user not logged in
if(!$this->session->userdata('loggedIn')){
redirect('/user_authentication/');
}
//get user info from session
$data['userData'] = $this->session->userdata('userData');
//load user profile view
$this->load->view('user_authentication/profile',$data);
}
public function logout(){
//delete login status & user info from session
$this->session->unset_userdata('loggedIn');
$this->session->unset_userdata('userData');
$this->session->sess_destroy();
//redirect to login page
redirect('/user_authentication/');
}
}
Models (application/models/User.php)
The User model contains one function called checkUser()
, it is used to insert or update the user profile information into the database.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class User extends CI_Model{
function __construct() {
$this->tableName = 'users';
$this->primaryKey = 'id';
}
public function checkUser($data = array()){
$this->db->select($this->primaryKey);
$this->db->from($this->tableName);
$this->db->where(array('oauth_provider'=>$data['oauth_provider'],'oauth_uid'=>$data['oauth_uid']));
$query = $this->db->get();
$check = $query->num_rows();
if($check > 0){
$result = $query->row_array();
$data['modified'] = date("Y-m-d H:i:s");
$update = $this->db->update($this->tableName,$data,array('id'=>$result['id']));
$userID = $result['id'];
}else{
$data['created'] = date("Y-m-d H:i:s");
$data['modified']= date("Y-m-d H:i:s");
$insert = $this->db->insert($this->tableName,$data);
$userID = $this->db->insert_id();
}
return $userID?$userID:false;
}
}
Views (application/views/)
user_authentication/index.php
This view file displays the login button to sign with Google account. This button redirects the user to the auth URL.
<h1>CodeIgniter Sign In With Google Account</h1> <a href="<?php echo $loginURL; ?>"><img src="<?php echo base_url().'assets/images/glogin.png'; ?>" /></a>
user_authentication/profile.php
This view shows the Google plus profile information with a logout link.
<h1>CodeIgniter Sign In With Google Account</h1> <div class="wrapper"> <div class="info-box"> <p class="image"><img src="<?php echo @$userData['picture_url']; ?>" width="300" height="220"/></p> <p><b>Google ID: </b><?php echo @$userData['oauth_uid']; ?></p> <p><b>Name: </b><?php echo @$userData['first_name'].' '[email protected]$userData['last_name']; ?></p> <p><b>Email: </b><?php echo @$userData['email']; ?></p> <p><b>Gender: </b><?php echo @$userData['gender']; ?></p> <p><b>Locale: </b><?php echo @$userData['locale']; ?></p> <p><b>Google+ Link: </b><a href="<?php echo @$userData['profile_url']; ?>" target="_blank"><?php echo @$userData['profile_url']; ?></a></p> <p><b>Logout from <a href="<?php echo base_url().'user_authentication/logout'; ?>">Google</a></b></p> </div> </div>
0 Comments