How to create google login in website using CodeIgniter

Hey friends, In this tutorial, we are going to create a system to authenticate users on your website via google. In short, we are going to create google login to integrate into your website.we follow following steps

  1. Add the website to the Google API console to get CLIENT ID.
  2. Create a database table to save user data.
  3. Create a CodeIgniter view (view contains a login form with google authentication javascript integrated with it).
  4. Create a CodeIgniter controller and Model to handle data provide by google login script after successful login.
  5. Create a view to display user data.

 Step 1: getting an CLIENT ID from Google.  

  1. Login to https://developers.google.com/identity/sign-in/web/sign-in and click on configure a project drop button.
    google login example

    google login example

  2. A modal box will appear, click on the Select or create project select button of the modal box. Then select Create a new project option and in next step specify the Project Name and then in next step create product name which will appear in API console.Click on next .

    google login integration in website example

     
     
  3. It will ask you to configure OAuth Client. In first select box select integration type i.e. web browser for our case, and in the second box enter your website URL where u want to integrate google login system. 
    google login system

  4. Click on create button, It will create a project and generates an CLIENT ID AND CLIENT SECRET. Copy it to a safe place.

generate api key and client secret

   5. You are ready now for next step. 

   Step 2: We will create a tbl_google_user table in MySQL database.

CREATE TABLE tbl_google_user
(
  user_id INT NOT NULL AUTO_INCREMENT,
  google_id VARCHAR(300) NOT NULL,
  user_name VARCHAR(255) NOT NULL,
  user_email VARCHAR(255) NOT NULL,
  img_url VARCHAR(255) NOT NULL,
  user_activation_time DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY(user_id)
);

We will create a login.php file in application/view/google/ folder to display google login button.If you are not using csrf then remove csrf_test_name value and variable.

<!doctype html>
<html lang="en">
  <head>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">


    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css" integrity="sha384-Smlep5jCw/wG7hdkwQ/Z5nLIefveQRIY9nfy6xoR1uRYBtpZgI6339F5dgvm/e9B" crossorigin="anonymous">

    <title>Hello, world!</title>
  </head>
  <body>
    <div class="container">
    	<div class="row justify-content-center m-5">
	<div class="col-12 col-sm-6 col-md-6 col-lg-4 col-xl-4">

                                    <a href="#" id="google-btn" class="btn btn-danger button btn-social googleplus span-left btn-block">
                                        <span><i class="fab fa-google-plus-g"></i>
                                        </span>Google+</a>

	</div>
</div>
<script>
	var csrf_test_name="<?/php echo $this->security->get_csrf_hash(); /?>";
	</script>
    </div>
    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/js/bootstrap.min.js" integrity="sha384-o+RDsa0aLu++PJvFqy8fFScvbHFLtbvScb8AjopnFD+iEQ7wo/CG0xlczd+2O/em" crossorigin="anonymous"></script>
    <div class="script">
	<script src="https://apis.google.com/js/platform.js" async defer></script>
    <script src="https://apis.google.com/js/api:client.js"></script>
    <script src="<?/php echo base_url("js/login/google.js");?>"></script>
	</div>
  </body>
</html>

create a google.js file at https://yourprojecturl/js/login  folder to integrate google login system. Please remove csrf_test_name variable if you are not using CodeIgniter's csrf feature . Please edit this file and insert your CLIENT ID at CLIENT ID field

$(document).ready(function(){
  var googleUser = {};
  var startApp = function() {
    gapi.load('auth2', function(){
      // Retrieve the singleton for the GoogleAuth library and set up the client.
      auth2 = gapi.auth2.init({
        client_id: 'XXXXXXXXXXXX-4sb8ebgf2j94v0e4j62ot28ot2r8mb75.apps.googleusercontent.com',
        cookiepolicy: 'none',
		  fetch_basic_profile:true,
		'scope': 'profile email',
    'accesstype': 'offline'
        // Request scopes in addition to 'profile' and 'email'
        //scope: 'additional_scope'
      });
      attachSignin(document.getElementById('google-btn'));
    });
  };

  function attachSignin(element) {

    auth2.attachClickHandler(element, {},
        function(googleUser) {

		 var name=googleUser.getBasicProfile().getName();
     var success= googleUser.isSignedIn();
            var id = googleUser.getAuthResponse().id_token;
            var email=googleUser.getBasicProfile().getEmail();
            var nick_name=googleUser.getBasicProfile().getGivenName();
            var img = googleUser.getBasicProfile().getImageUrl();
            //var id=googleUser.getBasicProfile().getId();
            $.ajax({
              url:'Google/google_user_signin',/*URL OF YOUR HANDLER FILE IT WILL BE YOUR
ROUTE FOR CLASS OR CAN BE FUNCTION NAME WITH CONTROLLER DIRECTLY */
              type:'POST',
              data:{success:success,id:id,img:img,name:name,nick_name:nick_name,email:email,'csrf_test_name':csrf_test_name},
              success:function(data){
             console.log(data);

                  var res=$.parseJSON(data);

                  if(res=='ok')
                  {
                      window.open("googleUser","_self");
                  }

                else  {
                    alert("server error");
                }
              }
        });
	}, function(error) {
          alert(JSON.stringify(error, undefined, 2));
        });
  }

      startApp();
  });

 We will create Google_model.php model file to handle data send by Controller class. It also checks user exists or not.

class Google_model extends CI_Controller
{
	public function __construct()
	{
		parent::__construct();
		$this->load->database();
	}
	public function check_user($email)
	{
		$this->db->select("*");
		$this->db->where("email",$email);
		$res=$this->db->get("tbl_google_user");
		if($res->num_rows()>0)
		{
			return TRUE;
		}
		else 
		{
			return FALSE;
		}
	}
	public function save_user_data($id,$name,$email,$img)
	{
		if($this->check_user($email)===FALSE)
		{
            $data=array("google_id"=>$id,"name"=>$name,"email"=>$email,"img_url"=>$img);
            if($this->db->insert("tbl_google_user",$data))
            {
            	
            	return true;
            }
            else
            {
            	return FALSE;
            }
        }
        else
        {$this->db->set("google_id",$id);
            	$this->db->set("name",$name);
            	$this->db->set("email",$email);
            	$this->db->set("img_url",$img);
            	$this->db->where("email",$email);
            	$this->db->update("tbl_google_user");
        	return TRUE;
        }
	}
	public function get_user_data($email)
	{
		$this->db->select("*");
		$this->db->where("email",$email);
		$res=$this->db->get("tbl_google_user");
		return $res->row_array();
	}
}

Controller file Google.php at application/controllers/ folder . it will contain all function to handle data obtained by google login API.

class Google extends CI_Controller
{
function __consturct()
{
parent::__construct();
load->model("Google_model");
 $this->load->library("session");
 }
 function test($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
   }
 public function google_login()
 {
        $this->load->view("google_login");
 }
 public function google_user_signin()
 {
 	$success=$this->test($this->input->post("success"));
 	$id=$this->test($this->input->post("id"));
 	$name=$this->test($this->input->post("name"));
 	$email=$this->test($this->input->post("email"));
 	$img=$this->test($this->input->post("img"));
 	if($this->Google_model->save_user_data($id,$name,$email,$img))
 	{
 		$res="ok";
 		$_SESSION["google_id"]=$id;
 		$_SESSION["email"];$_SESSION["response"]="ok";
 	}
 	else
 	{
 		$res="error";
 	}
echo json_encode($res);
 }
 public function get_google_user_data()
 {
 	if(isset($_SESSION["email"])&&(!empty($_SESSION["email"])))
 	{
 	$data["user"]=$this->Google_model->get_user_data($_SESSION["email"]);
 	$this->load->view("google/home",$data);
 	}
 	else
 	{
 		redirect("home");
 	}

 }
}

 A home.php file in application/view/google/ folder. To display data to user.

foreach($user as $key=>$value)
{
	if($key==="img_url")
	{
       echo'<img src="'.$value.'" width="100px" height="100px">';
	}
	else
	{
	echo $key."------>".$value."<br/>";	
	}
	

}

Now we will create a route at application/config/routes.php file

 

$route["google_login"]="Google/google_login";
$route["google_user_signin"]="Google/google_user_signin";
$route["googleUser"]="Google/get_google_user_data";

If you type goole_login after your site URL it will redirect you to the login page where the user can log in if exist it will update data on the database or it user not exist it will save a new user data to the database and send the user to the homepage. Check our implementation example here login example

Please notify us if code does not works at our support mail support@webtutorial.in

Other posts