Select Git revision
GoogleLogin.php
GoogleLogin.php 2.64 KiB
<?php
namespace RAP;
class GoogleLogin extends LoginHandler {
public function __construct(Locator $locator) {
parent::__construct($locator, Identity::GOOGLE);
}
public function login() {
// Retrieve Google configuration
$Google = $this->locator->config->authenticationMethods->Google;
$client = new \Google_Client(array(
'client_id' => $Google->id,
'client_secret' => $Google->secret,
'redirect_uri' => $this->locator->getBasePath() . $Google->callback,
));
// Ask permission to obtain user email and profile information
$client->setScopes(array(\Google_Service_People::USERINFO_EMAIL, \Google_Service_People::USERINFO_PROFILE));
if (isset($_REQUEST['logout'])) {
// Reset the access token stored into the session
unset($_SESSION['access_token']);
}
if (isset($_GET['code'])) {
// An access token has been returned from the auth URL.
$client->authenticate($_GET['code']);
$_SESSION['access_token'] = $client->getAccessToken();
}
if ($client->getAccessToken()) {
// Query web service for retrieving user information
$service = new \Google_Service_People($client);
try {
$res = $service->people->get('people/me', array('requestMask.includeField' => 'person.names,person.email_addresses'));
} catch (Google_Service_Exception $e) {
echo '<p>' . json_encode($e->getErrors()) . '</p>';
$thisPage = $PROTOCOL . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
echo '<p><a href="' . $thisPage . '?logout">Click here to unset the access token</a></p>';
}
$name = $res->getNames()[0]->getGivenName();
$surname = $res->getNames()[0]->getFamilyName();
$emailAddresses = [];
foreach ($res->getEmailAddresses() as $addr) {
array_push($emailAddresses, $addr->value);
}
$typedId = explode('/', $res->getResourceName())[1];
return $this->onIdentityDataReceived($typedId, function($identity) use($emailAddresses, $name, $surname) {
$identity->email = $emailAddresses[0];
$identity->name = $name;
$identity->surname = $surname;
});
} else {
// Redirect to Google authorization URL for obtaining an access token
$authUrl = $client->createAuthUrl();
header('Location: ' . $authUrl);
die();
}
return null;
}
}