Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Login with Google Plus OAuth using Cakephp

    • 0
    • 0
    • 0
    • 0
    • 3
    • 0
    • 0
    • 0
    • 2.43k
    Comment on it

    In this blog we will be integrating Google Plus OAuth Login functionality using Cakephp. So, let's start with the first foremost step, i.e, creating the Google Apps to get the Google OAuth Client Id and Client Secret Key.

     

    Step 1: Create Google app and get Google OAuth Client Id and Client Secret Key. For the same go through this link  . Log in with your Google account, then click on the Create Project button.

     

    Enter your project name and save

     

    Next you are required to enable Google+ API. Open your project, click on the Enable an API button (Overview - > Enable an API )

     

    Click on the Enable an API button (Overview - > Enable an API )

     

    Select Google + API from the list to enable.

     

    Now click on the Create Credentials button to create new client id

     

    Next you are required to enter some details on the consent screen like Email, Product Name, Home Page URL, Product Logo, Privacy Policy, etc

     

    Next, select and enter the application type, Authorised JavaScript Origin and Authorised Redirect URL.

    You have successfully created your client id, client secret. Note it down for further use.

     

    Step 2: Create sample database with table using the following SQL query:

    CREATE TABLE IF NOT EXISTS `users` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `first_name` varchar(60) DEFAULT NULL,
      `last_name` varchar(60) DEFAULT NULL,
      `email` varchar(80) DEFAULT NULL,
      `password` varchar(64) DEFAULT NULL,
      `social_id` varchar(45) DEFAULT NULL,
      `picture` varchar(100) DEFAULT NULL,
      `gender` char(1) DEFAULT NULL,
      `created` datetime DEFAULT NULL,
      `updated` datetime DEFAULT NULL,
      `uuid` varchar(70) DEFAULT NULL,
      `status` int(11) DEFAULT NULL,
      PRIMARY KEY (`id`),
      KEY `email_idx` (`email`)
    ) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1

     

    Step 3: Next we need Google API PHP script to make Oauth request to Google. For that download the latest version from the Github.

    Create folder Google in the app/vendor directory. Extract the zip folder the copy the src directory and paste it in the app/Vendor/Google directory.

     

    Step 4: Now create site_config.php file in the app/Config directory and paste the following lines of code into it. Replace your Client Id, Client Secret and Redirect URL

    <?php
    require_once 'messages.php';
    //db config
    define('DB_HOST', 'localhost');
    define('DB_NAME', 'cake_login');
    define('DB_USER', 'root');
    define('DB_PASS', '');
    define('DB_PREFIX', '');
    //site config
    define('BASE_PATH', 'http://localhost/cakelogin/');
    
    
    //Google App Details
    define('GOOGLE_APP_NAME', 'TestProject');
    define('GOOGLE_OAUTH_CLIENT_ID', 'YOUR CLIENT_ID');
    define('GOOGLE_OAUTH_CLIENT_SECRET', 'YOUR CLIENT_SECRET');
    define('GOOGLE_OAUTH_REDIRECT_URI', 'http://localhost/cakelogin/google_login');
    define("GOOGLE_SITE_NAME", 'http://localhost/');

    Include this site_config.php file in your bootstrap.php file in the app/Config directory.

     

    Step 5: Next create google_login.php file in the app/Config directory and include the following files. This is to include the Google PHP API script in our file to make any OAuth API request to Google.

    <?php
    /*******Google ******/
    require_once '../Vendor/Google/src/config.php';
    require_once '../Vendor/Google/src/Google_Client.php';
    require_once '../Vendor/Google/src/contrib/Google_PlusService.php';
    require_once '../Vendor/Google/src/contrib/Google_Oauth2Service.php';

     

    Step 6: Add Following two functions googlelogin() which will make Google OAuth login request, and google_login() which will handle Google OAuth login response from the Google, in your controller file.

    /**
     * This function will makes Oauth Api reqest
     */
    public function googlelogin()
    {
      $this->autoRender = false;
      require_once '../Config/google_login.php';
      $client = new Google_Client();
      $client->setScopes(array('https://www.googleapis.com/auth/plus.login', 'https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/plus.me'));
      $client->setApprovalPrompt('auto');
      $url = $client->createAuthUrl();
      $this->redirect($url);
    }
    
    /**
     * This function will handle Oauth Api response
     */
    public function google_login()
    {
      $this->autoRender = false;
      require_once '../Config/google_login.php';
      $client = new Google_Client();
      $client->setScopes(array('https://www.googleapis.com/auth/plus.login', 'https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/plus.me'));
      $client->setApprovalPrompt('auto');
    
      $plus       = new Google_PlusService($client);
      $oauth2     = new Google_Oauth2Service($client);
      if(isset($_GET['code'])) {
         $client->authenticate(); // Authenticate
         $_SESSION['access_token'] = $client->getAccessToken(); // get the access token here
      }
    
      if(isset($_SESSION['access_token'])) {
         $client->setAccessToken($_SESSION['access_token']);
      }
    
      if ($client->getAccessToken()) {
        $_SESSION['access_token'] = $client->getAccessToken();
        $user = $oauth2->userinfo->get();
        try {
          if(!empty($user)){
             $result = $this->User->findByEmail( $user['email'] );
             if(!empty( $result )){
                if($this->Auth->login($result['User'])){
                   $this->Session->setFlash(GOOGLE_LOGIN_SUCCESS, 'default', array( 'class' => 'message success'), 'success' );
                   $this->redirect(BASE_PATH);
                }else{
                   $this->Session->setFlash(GOOGLE_LOGIN_FAILURE, 'default', array( 'class' => 'message error'), 'error' );
                   $this->redirect(BASE_PATH.'login');
                 }
                                                    
              }else{
                $data = array();
                $data['email'] = $user['email'];
                $data['first_name'] = $user['given_name'];
                $data['last_name'] = $user['family_name'];
                $data['social_id'] = $user['id'];
                $data['picture'] = $user['picture'];
                $data['gender'] = $user['gender'] == 'male' ? 'm':'f';
                $data['uuid'] = CakeText::uuid();
                $this->User->save( $data );
                if($this->User->save( $data )){
                   $data['id'] = $this->User->getLastInsertID();
                   if($this->Auth->login($data)){
                      $this->Session->setFlash(GOOGLE_LOGIN_SUCCESS, 'default', array( 'class' => 'message success'), 'success' );
                      $this->redirect(BASE_PATH);
                   }else{
                      $this->Session->setFlash(GOOGLE_LOGIN_FAILURE, 'default', array( 'class' => 'message error'), 'error' );
                      $this->redirect(BASE_PATH.'login');
                   }
                                                            
                }else{
                   $this->Session->setFlash(GOOGLE_LOGIN_FAILURE, 'default', array( 'class' => 'message error'), 'error' );
                   $this->redirect(BASE_PATH.'login');
                }
              }
            }else{
               $this->Session->setFlash(GOOGLE_LOGIN_FAILURE, 'default', array( 'class' => 'message error'), 'error' );
               $this->redirect(BASE_PATH.'login');
             }
           }catch (Exception $e) {
               $this->Session->setFlash(GOOGLE_LOGIN_FAILURE, 'default', array( 'class' => 'message error'), 'error' );
               $this->redirect(BASE_PATH.'login');
            }
          }
    
         exit;
    }

     

    Step 7: Add the following link in your view file.

    <a class="btn btn-default google" href="<?php echo BASE_PATH.'googlelogin'; ?>">
       <i class="fa fa-google-plus modal-icons"></i> Signin with Google 
    </a>

     

    Step 8: Final step, allow user to access that two functions googlelogin() and google_login() without logging into our system in the beforeFilter() of the UserController

    public function beforeFilter()
    {
           $this->Auth->allow('google_login', 'googlelogin' );
           parent::beforeFilter();
    }

     

    That's all. For any query comment below.

    Happy Coding!

 3 Comment(s)

  • Thanks for the post, it's really helpful. Can you please tell me where I can get the following files.
    /*******Google ******/
    require_once '../Vendor/Google/src/config.php';
    require_once '../Vendor/Google/src/Google_Client.php';
    require_once '../Vendor/Google/src/contrib/Google_PlusService.php';
    require_once '../Vendor/Google/src/contrib/Google_Oauth2Service.php';

    I'm not getting the files in the API setup /src folder.

    Thanks for your help
Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: