eZ Community » Blogs » Thiago Campos Viana » Tip: Google Login sample code

By

Tip: Google Login sample code

Saturday 17 September 2011 4:02:10 pm

  • Currently 3 out of 5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

In this post I will show a sample code to get a working view that will do a google login using the new php client api.

You will need to create a module extension with one view, the anonymous user needs access to this view. You will also need to put the google php api src folder inside the classes or lib folder, remove all files from contrib folder but keep just the apiBuzzService.php. Also copy these two files to the lib/classes folder:

Check the tutorial about eZ publish extensions if you don't know yet how to create one.

You'll also need a googleapi.ini.append.php settings file with this format:

<?php /* #?ini charset="utf8"?
 
[APIAccess]
ClientId=xxx
ClientSecret=xxx
APIKey=xxx
 
 */
?>

So, you need to create you a google api console account, enable the buzz service and create your client id in api access. REMEMBER TO ADD YOUR SITE URL, INCLUDING yourmodule/view TO API ACCESS -> Redirect URIs.

Here's the magic code:

<?php
 
function genRandomString() {
    $length = 10;
    $characters = '0123456789abcdefghijklmnopqrstuvwxyz!@#$';
    $string = '';
 
    for ($p = 0; $p < $length; $p++) {
        $string .= $characters[mt_rand(0, strlen($characters))];
    }
 
    return $string;
}
 
function loadImageCURL($source, $save_to) {
    $ch = curl_init($source);
    $fp = fopen($save_to, "wb");
 
// set URL and other appropriate options
    $options = array(CURLOPT_FILE => $fp,
        CURLOPT_HEADER => 0,
        CURLOPT_FOLLOWLOCATION => 1,
        CURLOPT_TIMEOUT => 60); // 1 minute timeout (should be enough)
 
    curl_setopt_array($ch, $options);
 
    curl_exec($ch);
    curl_close($ch);
    fclose($fp);
}
 
$Module = $Params['Module'];
 
$ini = eZINI::instance('googleapi.ini');
$client = new apiClient();
$client->setApplicationName("GoogleLogin");
$client->setClientId($ini->variable("APIAccess", "ClientId"));
$client->setClientSecret($ini->variable("APIAccess", "ClientSecret"));
//$client->setDeveloperKey($ini->variable("APIAccess", "APIKey"));
 
$ini = eZINI::instance('site.ini');
// PLEASE EDIT WITH YOURMODULE/VIEW CORRECT NAME
$client->setRedirectUri(('http://' . $ini->variable("SiteSettings", "SiteURL") . '/yourmodule/view'));
 
//$client->setScopes(array('https://www.googleapis.com/auth/plus.me'));
$plus = new apiBuzzService($client);
 
if (isset($_GET['code'])) {
 
    $client->authenticate();
 
    $_SESSION['access_token'] = $client->getAccessToken();
}
 
 
 
if (isset($_SESSION['access_token'])) {
    $client->setAccessToken($_SESSION['access_token']);
}
 
 
 
if ($client->getAccessToken()) {
 
    unset($_SESSION['access_token']);
    try {
        $me = $plus->people->get('@me');
    } catch (Exception $e) {
        echo 'Error: not public profile';
        eZExecution::cleanExit();
    }
    $email = null;
    foreach ($me['emails'] as $m) {
        if ($m["primary"])
            $email = $m["value"];
    }
 
 
    $user = eZUser::fetchByEmail($email);
 
    if ($user instanceof eZUser) {
 
        eZUser::setCurrentlyLoggedInUser($user, $user->attribute('contentobject_id'));
        $Module->redirectTo('/');
    } else {
 
        $user = new ezpObject('user', 12, 14, 2);
        $name = explode(' ', $me["displayName"]);
        $first_name = $name[0];
        $last_name = implode(' ', array_slice($name, 1));
 
        $username = $email;
        $password = genRandomString();
 
        $image = 'var/cache/content/' . $password;
        loadImageCURL($me['thumbnailUrl'], $image);
 
        $user->__set("first_name", $first_name);
        $user->__set("last_name", $last_name);
        $user->__set("user_account", "$username|$username|" . md5("$username\n$password") . "|2");
        $user->__set("image", $image);
 
        $user->publish();
 
        unlink($image);
        $user = eZUser::fetchByEmail($email);
        eZUser::setCurrentlyLoggedInUser($user, $user->attribute('contentobject_id'));
        $Module->redirectTo('/');
    }
} else {
    $http = eZHTTPTool::instance();
    $http->redirect($client->createAuthUrl());
}
?>

Any suggestions to optimize this code? Please comment.

Proudly Developed with from