Google Login Integration in Codeigniter

 


 step by step process for integration of Login using Google Account in Codeigniter Framework.

  1. Create Google API Credential
  2. Download Google API php client library
  3. Define Autoload library
  4. Define Base Url of Codeigniter Application
  5. Make Database connection
  6. Create Controller
  7. Create Model
  8. Create View file

Create Google API Credential


For get Google API Credential, we need Google Account, if you have Google Account then you to first login into you account.

1 - If you are login into Google account, then you have to https://console.developers.google.com/ url.

2 - Once you have open above link, then first you have to create new project by click on create project link.




3 - After click on project link then new page will open, and here we have enter project name and click on create button.




4 - Next you can see newly created project on web page. And after this we have to click on OAuth consent screen link.






5 - After click on OAuth consent screen, then after new page has been load in browser, and here we can see two User Type option, and from that option we have to select External and click on Create button.




6 - Once we have click on Create button, then web page has redirect to new page, and on this page, we have to define Application Name and after this click on Save button.




7 - When we have click on Save button, then web page has redirect to this page. Here we can see our application details. Next we have to click on Credentials link at the left side menu.




8 - After click on Credentials link, then Credentials web page has been load in browser. And here we have to click on CREATE CREDENTIALS button.




9 - Once we have click on CREATE CREDENTIALS button, then one dropdown has been appear on web page with four option. And from that option, we have to select OAuth client ID link.




10 - When we have click on OAuth client ID option, then one new page has been load in browser and here we have to define Application Type from different option. So, from that option, we have to select Web Application.




11 - Once we have select Web Application, then below that field new field has been appear and in that field, we have to enter Name field details and define Authorized redirect Uris. This is for use with request from server, and lastly we have to click on Create button.




12 - Once we have click on Create button, then our Application has been register, and then after new page has been load with our application Client ID and Client secret key will appear on web page. We have to use both key in Codeigniter framework for make Login using Google Account.




2 - Download Google API php client library


Once we have get Google Client ID and Client Secret key, so next we have to download Google API Client Library for PHP script. So for this, first we have go to command prompt in which we have already install Composer command, and after this we have go to library folder of codeigniter framework in which we have to download library and run following command.


composer require google/apiclient:"^2.0"


This command will download Google API Client Library for PHP language in your define directory. Next we have proceed for write code in Codeigniter framework.

3 - Define Autoload library


In Codeigniter framework, we have to first define autoload library like database and session, so once we have define library, then we have do not want to again and again load in every method. For this we have to open application/config/autoload.php file.


$autoload['libraries'] = array('database','session');


4 - Define Base Url of Codeigniter Application


In Next step we have to define base url of your Codeigniter application. This is root url of you codeigniter application. For define Base url, we have to open application/config/config.php and write base url of your application.


$config['base_url'] = 'http://localhost/tutorial/codeigniter/';






5 - Make Database connection


Once we have define base url, next we want to make Msyql database connection. For this we have to open application/config/database.php and in that file we have to define database configuration.


$db['default'] = array(
 'dsn' => '',
 'hostname' => 'localhost',
 'username' => 'root',
 'password' => '',
 'database' => 'codeigniter_chat',
 'dbdriver' => 'mysqli',
 'dbprefix' => '',
 'pconnect' => FALSE,
 'db_debug' => (ENVIRONMENT !== 'production'),
 'cache_on' => FALSE,
 'cachedir' => '',
 'char_set' => 'utf8',
 'dbcollat' => 'utf8_general_ci',
 'swap_pre' => '',
 'encrypt' => FALSE,
 'compress' => FALSE,
 'stricton' => FALSE,
 'failover' => array(),
 'save_queries' => TRUE
);


6 - Create Controller


In Codeigniter framework, controller is used for handle http request. In Codeigniter framework controller class file has been store under application/controllers folder Here we have create controller with Google_login.php file name. In this controller here we have make following method.

__construct() - This is magic function code will be executed every time, when object of this class has been created.

login() - This method will communicate with Google Login Api by using Google API client library for PHP script. In this method we to set ClientIDClientSecret key and Redirect Uri which we have to define at the time creating credential process. Once this all has been set then we can send login request to Google server, then from server this method will received access token and based on that token user can login into website and get user data. If user data already store in our database, then this function will update data, otherwise it will insert user data in our database.

logout() - This method will received request from user to get permission for logout from system. In this method it has simply delete data from session variable and it will redirect page to login.

application/controllers/Google_login.php

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Google_login extends CI_Controller {

 public function __construct()
 {
  parent::__construct();
  $this->load->model('google_login_model');
 }

 function login()
 {
  include_once APPPATH . "libraries/vendor/autoload.php";

  $google_client = new Google_Client();

  $google_client->setClientId(''); //Define your ClientID

  $google_client->setClientSecret(''); //Define your Client Secret Key

  $google_client->setRedirectUri(''); //Define your Redirect Uri

  $google_client->addScope('email');

  $google_client->addScope('profile');

  if(isset($_GET["code"]))
  {
   $token = $google_client->fetchAccessTokenWithAuthCode($_GET["code"]);

   if(!isset($token["error"]))
   {
    $google_client->setAccessToken($token['access_token']);

    $this->session->set_userdata('access_token', $token['access_token']);

    $google_service = new Google_Service_Oauth2($google_client);

    $data = $google_service->userinfo->get();

    $current_datetime = date('Y-m-d H:i:s');

    if($this->google_login_model->Is_already_register($data['id']))
    {
     //update data
     $user_data = array(
      'first_name' => $data['given_name'],
      'last_name'  => $data['family_name'],
      'email_address' => $data['email'],
      'profile_picture'=> $data['picture'],
      'updated_at' => $current_datetime
     );

     $this->google_login_model->Update_user_data($user_data, $data['id']);
    }
    else
    {
     //insert data
     $user_data = array(
      'login_oauth_uid' => $data['id'],
      'first_name'  => $data['given_name'],
      'last_name'   => $data['family_name'],
      'email_address'  => $data['email'],
      'profile_picture' => $data['picture'],
      'created_at'  => $current_datetime
     );

     $this->google_login_model->Insert_user_data($user_data);
    }
    $this->session->set_userdata('user_data', $user_data);
   }
  }
  $login_button = '';
  if(!$this->session->userdata('access_token'))
  {
   $login_button = '<a href="'.$google_client->createAuthUrl().'"><img src="'.base_url().'asset/sign-in-with-google.png" /></a>';
   $data['login_button'] = $login_button;
   $this->load->view('google_login', $data);
  }
  else
  {
   $this->load->view('google_login', $data);
  }
 }

 function logout()
 {
  $this->session->unset_userdata('access_token');

  $this->session->unset_userdata('user_data');

  redirect('google_login/login');
 }
 
}
?>


7 - Create Model


Model class generally used for database related operation. In codeigniter framework, Model class has been store under application/models folder. Here we have create Models class with Google_login_model.php file. In this class we have make following method.

Is_already_register($id) - This method has been check user with $id variable value is already store in chat_user table or not. If user data is available then it will return true, otherwise it will return false.

Update_user_data($data, $id) - This method will update chat_user table data based on value of $id variable value.

Insert_user_data($data) - This method will insert data into chat_user table.

application/models/Google_login_model.php

<?php
class Google_login_model extends CI_Model
{
 function Is_already_register($id)
 {
  $this->db->where('login_oauth_uid', $id);
  $query = $this->db->get('chat_user');
  if($query->num_rows() > 0)
  {
   return true;
  }
  else
  {
   return false;
  }
 }

 function Update_user_data($data, $id)
 {
  $this->db->where('login_oauth_uid', $id);
  $this->db->update('chat_user', $data);
 }

 function Insert_user_data($data)
 {
  $this->db->insert('chat_user', $data);
 }
}
?>





8 - Create View file


This file is used for display html output in browser. In Codeigniter framework view file has been store in application/views folder. Here we have create views file with google_login.php name.

application/views/google_login.php

<html>
 <head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>Login with Google in Codeigniter</title>
  <meta content='width=device-width, initial-scale=1, maximum-scale=1' name='viewport'/>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
  
 </head>
 <body>
  <div class="container">
   <br />
   <h2 align="center">Login using Google Account with Codeigniter</h2>
   <br />
   <div class="panel panel-default">
   <?php
   if(!isset($login_button))
   {

    $user_data = $this->session->userdata('user_data');
    echo '<div class="panel-heading">Welcome User</div><div class="panel-body">';
    echo '<img src="'.$user_data['profile_picture'].'" class="img-responsive img-circle img-thumbnail" />';
    echo '<h3><b>Name : </b>'.$user_data["first_name"].' '.$user_data['last_name']. '</h3>';
    echo '<h3><b>Email :</b> '.$user_data['email_address'].'</h3>';
    echo '<h3><a href="'.base_url().'google_login/logout">Logout</h3></div>';
   }
   else
   {
    echo '<div align="center">'.$login_button . '</div>';
   }
   ?>
   </div>
  </div>
 </body>
</html>

Comments

Popular posts from this blog

Codeigniter Pro Level Tips and Tricks

Login with Facebook in CodeIgniter

PHP - File Uploading