Sunday, September 3, 2017

Login with Google Account in CodeIgniter ?


Follow some steps:

Before you start the coding some points are remember :

  =>Create a google developer account for client id and client secret key.


1. Flow chart of codeigniter files...

2. First go to your controller...User_authentication.php and past this code shown below:

  <?php defined('BASEPATH') OR exit('No direct script access allowed');
class User_Authentication extends CI_Controller{
    function __construct() {
        parent::__construct();
        // Load user model
        $this->load->model('user');
    }
    
    public function index(){
        // Include the google api php libraries
        include_once APPPATH."libraries/google-api-php-client/Google_Client.php";
        include_once APPPATH."libraries/google-api-php-client/contrib/Google_Oauth2Service.php";
        
        // Google Project API Credentials
        $clientId 'Insert Google Client ID';
        $clientSecret 'Insert Google Client secret';
        $redirectUrl base_url() . 'user_authentication/';
        
        // Google Client Configuration
        $gClient = new Google_Client();
        $gClient->setApplicationName('Login to codexworld.com');
        $gClient->setClientId($clientId);
        $gClient->setClientSecret($clientSecret);
        $gClient->setRedirectUri($redirectUrl);
        $google_oauthV2 = new Google_Oauth2Service($gClient);

        if (isset($_REQUEST['code'])) {
            $gClient->authenticate();
            $this->session->set_userdata('token'$gClient->getAccessToken());
            redirect($redirectUrl);
        }

        $token $this->session->userdata('token');
        if (!empty($token)) {
            $gClient->setAccessToken($token);
        }

        if ($gClient->getAccessToken()) {
            $userProfile $google_oauthV2->userinfo->get();
            // Preparing data for database insertion
            $userData['oauth_provider'] = 'google';
            $userData['oauth_uid'] = $userProfile['id'];
            $userData['first_name'] = $userProfile['given_name'];
            $userData['last_name'] = $userProfile['family_name'];
            $userData['email'] = $userProfile['email'];
            $userData['gender'] = $userProfile['gender'];
            $userData['locale'] = $userProfile['locale'];
            $userData['profile_url'] = $userProfile['link'];
            $userData['picture_url'] = $userProfile['picture'];
            // Insert or update user data
            $userID $this->user->checkUser($userData);
            if(!empty($userID)){
                $data['userData'] = $userData;
                $this->session->set_userdata('userData',$userData);
            } else {
               $data['userData'] = array();
            }
        } else {
            $data['authUrl'] = $gClient->createAuthUrl();
        }
        $this->load->view('user_authentication/index',$data);
    }
    
    public function logout() {
        $this->session->unset_userdata('token');
        $this->session->unset_userdata('userData');
        $this->session->sess_destroy();
        redirect('/user_authentication');
    }
}

3. Than go to Model : User.php and past this code...

<?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']));
        $prevQuery $this->db->get();
        $prevCheck $prevQuery->num_rows();
        
        if($prevCheck 0){
            $prevResult $prevQuery->row_array();
            $data['modified'] = date("Y-m-d H:i:s");
            $update $this->db->update($this->tableName,$data,array('id'=>$prevResult['id']));
            $userID $prevResult['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;
    }
}

4. Create  a view page : index.php and past this code....

<?phpif(!empty($authUrl)) {
    echo '<a href="'.$authUrl.'"><img src="'.base_url().'assets/images/glogin.png" alt=""/></a>';
}else{
?><div class="wrapper">
    <h1>Google Profile Details </h1>
    <?php
    echo '<div class="welcome_txt">Welcome <b>'.$userData['first_name'].'</b></div>';
    echo '<div class="google_box">';
    echo '<p class="image"><img src="'.$userData['picture_url'].'" alt="" width="300" height="220"/></p>';
    echo '<p><b>Google ID : </b>' $userData['oauth_uid'].'</p>';
    echo '<p><b>Name : </b>' $userData['first_name'].' '.$userData['last_name'].'</p>';
    echo '<p><b>Email : </b>' $userData['email'].'</p>';
    echo '<p><b>Gender : </b>' $userData['gender'].'</p>';
    echo '<p><b>Locale : </b>' $userData['locale'].'</p>';
    echo '<p><b>Google+ Link : </b>' $userData['profile_url'].'</p>';
    echo '<p><b>You are login with : </b>Google</p>';
    echo '<p><b>Logout from <a href="'.base_url().'user_authentication/logout">Google</a></b></p>';
    echo '</div>';
    ?></div>
<?php ?>

it's all over process to sign in using google account....