CodeIgniter Tutorial - Cara Membuat System Login yang Terintegrasi dengan Akun Google

 




Buat sebuah table untuk menyimpan data User yang melakukan login dengan akun google. Adapun struktur tablenya seperti dibawah ini:

CREATE TABLE `chat_user` (
	`user_id` INT(11) NOT NULL AUTO_INCREMENT,
	`login_oauth_uid` VARCHAR(100) NULL DEFAULT NULL,
	`first_name` VARCHAR(100) NULL DEFAULT NULL,
	`last_name` VARCHAR(100) NULL DEFAULT NULL,
	`email_address` VARCHAR(100) NULL DEFAULT NULL,
	`profile_picture` VARCHAR(100) NULL DEFAULT NULL,
	`created_at` DATETIME NULL DEFAULT NULL,
	`updated_at` DATETIME NULL DEFAULT NULL,
	PRIMARY KEY (`user_id`)
)
Setelah membuat table, kunjungi https://console.developers.google.com/. Untuk bisa terintegrasi dengan API Google Account, ikuti langkah-langkah berikut:

1. Pada Menu Dashboard buat project baru dengan nama Pasir Ganting Demo (Penamaan bebas)



2. Pada Menu Kredensial, kita perlu untuk mendapatkan Cleint ID dan Secret Key nya, untuk mendapatkan hal tersebut lihat gambar.




3. Pada menu Layar Persetujuan Oauth, ikuti langah pada gambar dibawah ini sampai ke tahap 4



Setelah melakukan 3 langkah diatas, let's start to code dude!

Google_login.php (Controller)
<?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');
        date_default_timezone_set("Asia/Jakarta");
    }
   public function login()
    {
        require "vendor/autoload.php";
        $google_client = new Google_Client();

        $google_client->setClientId('Your Client ID Here'); //Define your ClientID

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

        $google_client->setRedirectUri('http://localhost/blog/google_login/login'); //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().'sign-with-google.png" /></a>';
                    $data['login_button'= $login_button;
                    $this->load->view('google_login'$data);
                }
                else
                {
                    $this->load->view('google_login'$data);
                }
    }


    public function logout()
    {
        $this->session->unset_userdata('access_token');
        $this->session->unset_userdata('user_data');
        redirect('google_login/login');
    }
}

?>

2. Google_login_model.php (Model)
<?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);
    }
}


3. Google_login.php (View)
<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' />
    <!-- CDN Bootstrap -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
    <!-- CDN Jquery -->
    <script src="https://code.jquery.com/jquery-3.5.1.js" integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous"></script>
    <script src="https://use.fontawesome.com/07323268fb.js"></script>

</head>

<body>
    <div class="container">
        <br />
        <h2 align="center">Login Menggunakan Akun Google dengan 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>
Untuk menjalankan program silahkan kunjungi http://localhost/blog/google_login/login

Demo Program


Semoga bermanfaat!!!

Posting Komentar

3 Komentar

  1. itu google client dari mana ya gan ?

    BalasHapus
    Balasan
    1. rasanya dari composer, composer require google/apiclient

      Hapus
  2. ada link youtube untuk tutorial ini?

    BalasHapus