Trying to use referesh tokens with google PHP api - php

This is my first time implementing login via google and I am a beginner programmer. I have been stuck on implementing refresh tokens using google api and outh 2.
Here is the code I am using to implement the login
<?php
ob_start();
session_start();
require_once 'init.php';
require('vendor/autoload.php');
//Details for setting up the google login
$client = new Google_Client();
$client->setAccessType("offline");
$client->setAuthConfigFile('client_secrets.json');
$client->setScopes(array('https://www.googleapis.com/auth/plus.login','https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/plus.me'));
$oauth2 = new Google_Service_Oauth2($client);
/************************************************
Logout function
************************************************/
if (isset($_REQUEST['logout'])) {
unset($_SESSION['token']);
$client->revokeToken();
header('Location:http://localhost:1234/trial/log-inlogic/');
}
/************************************************
Get the code back from the OAuth 2.0 flow,
exchange that with the authenticate()
function.
************************************************/
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['token'] = $client->getAccessToken();
header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
}
/************************************************
If we have an access token, I make
requests, else I generate an authentication URL.
************************************************/
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
else {
$authUrl = $client->createAuthUrl();
}
/************************************************
In case the token is expired, this is where i have a problem
************************************************/
if ($client->getAccessToken()) {
//Check if our token has expired.
if ($client->isAccessTokenExpired()) {
// create this function to store the referesh token in the database
$refreshToken = getRefreshToken();
$client->refreshToken($refreshToken);
}
//Basic User Information
$user = $oauth2->userinfo->get();
try {
google_login( $user );
}catch (Exception $e) {
$error = $e->getMessage();
}
$_SESSION['token']=$client->getAccessToken();
//Save the refresh token on our database.
}
//Simple function to store a given refresh_token on a database
function setRefreshToken () {
if (isset($_SESSION['k_id'])) {
$k_id=$_SESSION['k_id'];
$accesstoken=$_SESSION['token'];
$token=json_decode($_SESSION['token']);
echo $token->refresh_token;
$result =query("UPDATE users SET refreshtoken=$token WHERE k_id='$k_id'");
}
}
//Retrieves the refresh_token from our database.
function getRefreshToken () {
if (isset($_SESSION['k_id'])) {
$k_id=$_SESSION['k_id'];
$result = query("SELECT refresh_token FROM users WHERE k_id='$k_id'");
if(count($result)==0){
}
else{
return $result[0]['refresh_token'];
}
}
}
function google_login($user )
{
// escape variables for security
$name = $user['name'];
$email = $user['email'] ;
$social_id = $user['id'] ;
$picture = $user['picture'] ;
$result = query("SELECT k_id FROM users where email = '$email'");
$count = count($result);
if( $count == 1){
$_SESSION['logged_in'] = true;
$_SESSION['k_id']=$result[0]['k_id'];
$result = query("SELECT gog_id FROM users where email = '$email'");
if($result[0]['gog_id']){
setRefreshToken();
}
else{
$add_user = query("INSERT INTO users (gog_id) VALUES(?)", $social_id);
}
}else{
$add_user = query("INSERT INTO users (gog_id, email, name, pic) VALUES(?, ?, ?, ?)", $social_id, $email, $name, $picture);
if( $add_user === false)
{
apologize("Whoops! There was an error at our end. We deeply apologisze.");
}
//the new user has been added
$return_id = query("SELECT k_id FROM users WHERE gog_id = ?", $social_id);
//storing the user id in session superglobal
$_SESSION["k_id"]=$return_id[0]["k_id"];
}
}
?>
<?php ob_end_flush(); ?>
The problem I have is in the setRefreshToken() function. This the error I get
Notice: Undefined property: stdClass::$refresh_token in C:\xampp\htdocs\trial\log-inlogic\config.php on line 88
Catchable fatal error: Object of class stdClass could not be converted to string in C:\xampp\htdocs\trial\log-inlogic\config.php on line 89
Can someone tell me what might be the problem, I have researched online and all the people are recommending the same solution.

The error in
Notice: Undefined property: stdClass::$refresh_token in C:\xampp\htdocs\trial\log-inlogic\config.php on line 88
is because the server didn't return a refresh token in the response. You can solve this by revoking the access and granting it again by using $client->revokeToken()
Catchable fatal error: Object of class stdClass could not be converted to string in C:\xampp\htdocs\trial\log-inlogic\config.php on line 89
This is because you are trying to write an object as a string
$result =query("UPDATE users SET refreshtoken=$token WHERE k_id='$k_id'");
try this instead
$result =query("UPDATE users SET refreshtoken='$token->refresh_token' WHERE k_id='$k_id'");

Related

"Login with Google" in PHP - Google+ API shutdown migration - how to migrate away from plus.people.get?

I got a warning email from Google reminding me of Google+'s EOL which is supposed to break my current "Login with Google", but I am unsure what exactly should I change.
Let me show you my (simplified) login code:
google-login.php
new class {
public function __construct() {
$state = mt_rand();
$client = new Google_Client();
$client->setApplicationName(Config::Google['app_name']);
$client->setClientId(Config::Google['id']);
$client->setClientSecret(Config::Google['secret']);
$client->setRedirectUri(sprintf('https://%s/members/google-callback.php', $_SERVER['HTTP_HOST']));
$client->setScopes(['profile', 'email']);
$client->setState($state);
$_SESSION['state'] = $state;
$url = $client->createAuthUrl(); // $url = https://accounts.google.com/o/oauth2/auth?response_type=code&access_type=online&client_id=CLIENT_ID.apps.googleusercontent.com&redirect_uri=https%3A%2F%2Fread2me.online%2Fmembers%2Fgoogle-callback.php&state=1588245f23f2a&scope=profile%20email&approval_prompt=auto
header ("location: $url");
}
};
google-callback.php
new class {
private $newUser = false;
public function __construct() {
if (!isset($_GET['state']) || $_GET['state'] != $_SESSION['state'])
die('State mismatch.');
$client = new Google_Client();
$client->setApplicationName(Config::Google['app_name']);
$client->setClientId(Config::Google['id']);
$client->setClientSecret(Config::Google['secret']);
$client->setRedirectUri(sprintf('https://%s/members/google-callback.php', $_SERVER['HTTP_HOST']));
$client->setScopes(['profile', 'email']);
$plus = new Google_Service_Plus($client);
if (isset($_GET['code'])) {
$client->fetchAccessTokenWithAuthCode($_GET['code']);
$_SESSION['token'] = $client->getAccessToken();
}
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
if (!$client->getAccessToken() || $client->isAccessTokenExpired()) {
$state = mt_rand();
$client->setState($state);
$_SESSION['state'] = $state;
$url = $client->createAuthUrl();
header ("location: $url");
}
try {
$me = $plus->people->get('me');
} catch (Google_Exception $e) {
\Rollbar::report_message($e->getMessage());
print_r($e->getMessage());
return;
}
$accessToken = $client->getAccessToken()['access_token'];
$email = $me->getEmails()[0]->getValue();
$name = $me->getDisplayName();
$avatar = $me->getImage()->getUrl();
$id = $me->getId();
if ($this->isEmailInSystem($email) === false) {
$this->newUser = true;
$this->addUser($email, $name, 'google', $accessToken, $id, $avatar);
}
header ("location: " . '/');
}
};
Now, I'm going through at what seems to be the up-to-date Sign In guide for PHP, but I am not sure what to change - any ideas?
Thanks
The best migration is to move from the Plus API to the People API, which provides access to the user's profile in a similar (tho not quite identical) way.
You would replace the creation of the $plus object with a new Goolge_Service_PeopleService object. Something like
$people = new Google_Service_PeopleService( $client );
Getting the profile is more involved since you need to specify which fields from the profile you want to get. But you might do it something like
$profile = $people->people->get(
'people/me',
array('personFields' => 'names,emailAddresses,photos')
);
The first parameter needs to be "people/me" to specify that you're requesting the authorized user's profile.
The second is an array of query parameters. You need to specify the "personFields" that you want from the list of what is available (scroll down on this page till you see the description of the available fields) and specify this as a comma separated list in a string. In my example above, I illustrate getting the name, email addresses, and photos. But consult the list and experiment.
The exact fields you get from the result in $profile will be different than those you got from $plus, but they should match the fields you requested. Check the values and exactly how they're structured.
I ran into the same issue as Google+ APIs shutting down on March 7, 2019.
Make sure Google People API is enable in your google console
I used google-api-php-client Library.
Once you have an access token here is code to get the person object using people API
$accessToken = 'REPLACE_WITH_ACCESS_TOKEN';
$clientId = 'REPLACE_WITH_CLIENT_ID';
$clientSecret = 'REPLACE_WITH_CLIENT_SECRET';
$developerKey = 'REPLACE_WITH_DEVELOPER_KEY';
$client = new Google_Client();
$client->setApplicationName("Application Name");
$client->setClientId($clientId . '.apps.googleusercontent.com');
$client->setClientSecret($clientSecret);
$client->setDeveloperKey($developerKey);
$client->setScopes(['https://www.googleapis.com/auth/userinfo.email','https://www.googleapis.com/auth/userinfo.profile']);
$client->setAccessToken($accessToken);
$guzzleClient = new \GuzzleHttp\Client(array( 'curl' => array( CURLOPT_SSL_VERIFYPEER => false, ), ));
$client->setHttpClient($guzzleClient);
$people = new Google_Service_PeopleService( $client );
if ($client->getAccessToken()) {
try {
$me = $people->people->get(
'people/me',
array('personFields' => 'emailAddresses,names,photos')
);
$id = preg_replace('/[^0-9]/', '', $me->getResourceName());
$email = $me->getEmailAddresses()[0]->value;
$name = $me->getNames()[0]->displayName;
$avtar = $me->getPhotos()[0]->getUrl();
} catch (Google_Exception $e) {
// error
echo $e->getMessage();
}
}
I also disabled Google+ API to make sure the application is not using it anymore anywhere.
With latest version of Google API PHP Client you can fetch profile details from Google_Client object itself.
$token = $client->fetchAccessTokenWithAuthCode($_GET['code']);
$attributes = $client->verifyIdToken($token['id_token'], GOOGLE_CLIENT_ID);
print_r($attributes);
Refer this article.
Obviously, the lines
$plus = new Google_Service_Plus($client);
and
$me = $plus->people->get('me');
You need to use google email API, see https://developers.google.com/gmail/api/quickstart/php , so the first line will be
$service = new Google_Service_Gmail($client);
and second ... hmmm ... not sure there WILL be any avatar after removing of google plus ...

How can i navigate to same page after successful google/facebook login?

I have create a website using php which is having google and facebook login. This website having 6 pages. For all the 6 pages header and footer are common(included). Assume I am login into the site using google from page 5. After successful/failure login, the page navigate to index.php (page 1) instead of page5. How can i navigate to the same page after successful/failure login of google and facebook. Is this possible without adding all the pages in google/facebook developer console?
Also i have tried to change the header location after successful login. It throws cannot reach, out of time error. Can any one help to solve this problem. Thanks in advance.
Note: I am using google and facebook Oauth service for login.
Here is my code:
google login.
<?php
session_start();
require_once 'dbconnection.php';
//Google API PHP Library includes
require_once 'gvendor/vendor/autoload.php';
require_once 'gvendor/vendor/google/apiclient/src/Google/Client.php';
require_once 'gvendor/vendor/google/apiclient/src/Google/Service/Oauth2.php';
// Fill CLIENT ID, CLIENT SECRET ID, REDIRECT URI from Google Developer Console
$client_id = 'xxxxxxx';
$client_secret = 'xxxxxxx';
$redirect_uri = 'http://localhost:80/tthtml/index.php';
$simple_api_key = 'xxxxxxx';
global $googleauthUrl;
//Create Client Request to access Google API
$client = new Google_Client();
$client->setApplicationName("PHP Google OAuth Login Example");
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);
$client->setDeveloperKey($simple_api_key);
$client->addScope("https://www.googleapis.com/auth/userinfo.email");
$client->setAccessType('offline');
//Send Client Request
$objOAuthService = new Google_Service_Oauth2($client);
try{
//Logout
if (isset($_REQUEST['logout'])) {
$client->revokeToken($_SESSION['access_token']);
unset($_SESSION['access_token']);
unset($_SESSION['google_user_name']);
session_unset();
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL)); //redirect user back to page
}
//Authenticate code from Google OAuth Flow
//Add Access Token to Session
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['access_token'] = $client->getAccessToken();
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
//Set Access Token to make Request
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
$client->setAccessToken($_SESSION['access_token']);
}
//Get User Data from Google Plus
//If New, Insert to Database
if ($client->getAccessToken()) {
$userData = $objOAuthService->userinfo->get();
$_SESSION['google_user_name']=$userData['given_name'];
$_SESSION['user_id']=$userData->id;
if(!empty($userData)) {
$dbObj=new database();
$dbObj->openconnection();
$sql='select * from tttbl_user where google_fb_id='.$userData->id;
$existing_member = $dbObj->existingMember($sql);
if(empty($existing_member)) {
$sql="insert into tttbl_user (google_fb_id, user_name, gender, email_id, gplus_link, profile_photo, created_date) values('".$userData->id."','".$userData->name."','".$userData->gender."','".$userData->email."','".$userData->link."','".$userData->picture."',now())";
$dbObj->newUser($sql);
}
$dbObj->closeconnection();
}
}
else{
$googleauthUrl = $client->createAuthUrl();
}
}
catch(Exception $ee)
{ }
?>
facebook login
<?php //
//ob_start();
session_start();
require_once 'dbconnection.php';
require_once 'fvendor/vendor/autoload.php';
require_once 'fvendor/vendor/facebook/php-sdk/src/facebook.php';
// Create our Application instance (replace this with your appId and secret).
global $facebook_loginUrl;
$appId='xxxxxx';
$secretkey='xxxxxx';
$facebook = new Facebook(array(
'appId' => 'xxxxxxx',
'secret' => 'xxxxxxxx',
));
// Get User ID
$fb_user = $facebook->getUser();
if(isset($_REQUEST['fb_logout'])){
//$accessToken=null;
//$logoutUrl = $helper->getLogoutUrl($_SESSION['facebook_access_token'], 'http://localhost/fblogin/fblogin.php');
//unset($_SESSION['facebook_access_token']);
unset($_SESSION['facebook_user_name']);
session_unset();
session_destroy();
$fb_user = null;
header('Location: http://localhost:80/tthtml/index.php');
}
if ($fb_user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$uid = $facebook->getUser();
$user_profile = $facebook->api('/me?fields=id,name,picture,email,gender');
}
catch (FacebookApiException $e) {
error_log($e);
$fb_user = null;
}
}
else
{
$facebook_loginUrl = $facebook->getLoginUrl(array('scope' => 'email,user_birthday,user_photos','req_perms' => 'user_mobile_phone',));
$facebookurlstring=$facebook_loginUrl;
$x=strpos($facebookurlstring,'redirect_uri=');
$y=strpos($facebookurlstring, 'state');
$facebookurllength= strlen($facebookurlstring);
//substr($str,0,$y+13).'http://localhost/tthtml/index.php'.substr($str, $y+13+$x,$length)
$facebook_loginUrl=substr($facebookurlstring,0,$x+13).'http://localhost/tthtml/index.php'.substr($facebookurlstring, $y-1,$facebookurllength);
}
if($fb_user)
{
$userid=$user_profile['id'];
$username = $user_profile['name'];
$useremail = $user_profile['email'];
$userpicture=$user_profile['picture']['data']['url'];
$usergender=$user_profile['gender'];
$mobilenumber=$user_profile['user_mobile_phone'];
$_SESSION['facebook_user_name']=$username;
$_SESSION['user_id']=$userid;
if(isset($_SESSION['facebook_user_name'])&& $_SESSION['facebook_user_name']) {
$dbObj=new database();
$dbObj->openconnection();
$sql='select * from tttbl_user where google_fb_id='.$userid.';';
$existing_member = $dbObj->existingMember($sql);
if(empty($existing_member)) {
$sql="insert into tttbl_user (google_fb_id, user_name, gender, email_id, profile_photo, created_date)"
. " values('".$userid."','".$username."','".$usergender."','".$useremail."','".$userpicture."',now())";
$dbObj->newUser($sql);
}
$dbObj->closeconnection();
}
}
?>
If I change the redirect URI, it will search in the URL list in developer console. If it is not available in the list of developer console, then it throws ulr is not available in whitelist(for facebook) and page not found (for google) error is thrown.
Try to redirect with jQuery code
echo "<script>window.location.href ='yourpage.php';</script>";

How to get this session working in Google login php?

I am logging a user using Google login. I have included all the necessary files needed for Google login. I have created a PHP script for log-in. I have all my authentication and redirection info in place. However, I do not understand why am I not getting email field which I am getting from googleClient in my session. Please help.
Here is my code:
<?php
$google_client_id = '#########.apps.googleusercontent.com';
$google_client_secret = 'xxxxxxxxxxxxxxxxxxx';
$google_redirect_url = 'http://localhost/project/profile.php';
$google_developer_key = '';
//include google api files
require_once '../src/Google_Client.php';
require_once '../src/contrib/Google_Oauth2Service.php';
session_start();
$gClient = new Google_Client();
$gClient->setClientId($google_client_id);
$gClient->setClientSecret($google_client_secret);
$gClient->setRedirectUri($google_redirect_url);
$google_oauthV2 = new Google_Oauth2Service($gClient);
if (isset($_REQUEST['reset']))
{
unset($_SESSION['token']);
$gClient->revokeToken();
header('Location: ' . filter_var($google_redirect_url, FILTER_SANITIZE_URL));
}
if (isset($_GET['code']))
{
$gClient->authenticate($_GET['code']);
$_SESSION['token'] = $gClient->getAccessToken();
header('Location: ' . filter_var($google_redirect_url, FILTER_SANITIZE_URL));
return;
}
if (isset($_SESSION['token']))
{
$gClient->setAccessToken($_SESSION['token']);
}
if ($gClient->getAccessToken())
{
//Get user details if user is logged in
$user = $google_oauthV2->userinfo->get();
$user_id = $user['id'];
$user_name = filter_var($user['name'], FILTER_SANITIZE_SPECIAL_CHARS);
$email = filter_var($user['email'], FILTER_SANITIZE_EMAIL);
$profile_url = filter_var($user['link'], FILTER_VALIDATE_URL);
$profile_image_url = filter_var($user['picture'], FILTER_VALIDATE_URL);
$personMarkup = "$email<div><img src='$profile_image_url?sz=50'></div>";
$_SESSION['token'] = $gClient->getAccessToken();
$_SESSION['email'] = $email;
}
else
{
//get google login url
$authUrl = $gClient->createAuthUrl();
}
?>
My profile.php looks like this -
It results in -
Notice: Undefined index: email on line 4
After this script runs, the control jumps to the next page where it says that email is not found in session. Should I create a new Google_Client()? Whats the proper way to do this series of interaction after login?
First of all it will work on localhost, no problem. Because I have just created google and facebook login and it works fine.
you need to add Google ClientID and Client secret key from the console developer google where you have created web app and ouath key.
In main Login page you can redirect to another page...
/*! \brief Configure the client object
* Exchange authorization code for refresh and access tokens
*/
if (isset($_GET['code'])) {
$gClient->authenticate($_GET['code']);
$_SESSION['token'] = $gClient->getAccessToken(); /**< retrieve the access token with the getAccessToken method */
header('Location: ' . filter_var($redirectURL, FILTER_SANITIZE_URL)); /**< Redirect the user to $auth_url: */
}
if (isset($_SESSION['token'])) {
$gClient->setAccessToken($_SESSION['token']); /**< apply an access token to a new Google_Client object */
}
$authUrl = $gClient->createAuthUrl(); /**< Generate a URL to request access from Google's OAuth 2.0 server */
Try this..
!(set($_GET['code'])) {
$gClient->authenticate($_GET['code']);
$_SESSION['token'] = $gClient->getAccessToken(); /**< retrieve the access token with the getAccessToken method */
header('Location: ' . filter_var($redirectURL, FILTER_SANITIZE_URL)); /**< Redirect the user to $auth_url: */ }
if (isset($_SESSION['token'])) {
$gClient->setAccessToken($_SESSION['token']); /**< apply an access token to a new Google_Client object */
})

oauth2 access token expire

<?php
session_start();
require_once realpath(dirname(__FILE__) . '/Google/src/Google/autoload.php');
/************************************************
ATTENTION: Fill in these values! Make sure
the redirect URI is to this page, e.g:
http://localhost:8080/user-example.php
************************************************/
$client_id = 'xxxxx-1l76cd2vi4ik5oqm5s20nj965riu4hum.apps.googleusercontent.com';
$client_secret = 'secret';
$redirect_uri = 'http://www.audit.polydevs.co.uk/oauth2callback.php?login';
$client = new Google_Client();
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);
$client->setScopes('email');
/************************************************
If we're logging out we just need to clear our
local access token in this case
************************************************/
if (isset($_REQUEST['logout'])) {
unset($_SESSION['access_token']);
header("Location: login.php");
}
if (isset($_REQUEST['logoutInvalid'])) {
unset($_SESSION['access_token']);
header("Location: login.php?invalid");
}
/************************************************
If we have a code back from the OAuth 2.0 flow,
we need to exchange that with the authenticate()
function. We store the resultant access token
bundle in the session, and redirect to ourself.
************************************************/
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['access_token'] = $client->getAccessToken();
$redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}
/************************************************
If we have an access token, we can make
requests, else we generate an authentication URL.
************************************************/
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
$client->setAccessToken($_SESSION['access_token']);
} else {
$authUrl = $client->createAuthUrl();
}
/************************************************
If we're signed in we can go ahead and retrieve
the ID token, which is part of the bundle of
data that is exchange in the authenticate step
- we only need to do a network call if we have
to retrieve the Google certificate to verify it,
and that can be cached.
************************************************/
if ($client->getAccessToken()) {
$_SESSION['access_token'] = $client->getAccessToken();
$token_data = $client->verifyIdToken()->getAttributes();
}
if($client->isAccessTokenExpired()) {
echo 'Access Token Expired'; // Debug
$client->authenticate;
$newAccessToken = json_decode($client->getAccessToken());
$client->refreshToken($newAccessToken->refresh_token);
}
if (strpos($client_id, "googleusercontent") == false) {
echo missingClientSecretsWarning();
exit;
}
if (isset($_REQUEST['login'])) {
if (isset($authUrl)) {
header('Location:'.$authUrl);
} else {
require_once('func/connect.php');
$query = "SELECT * FROM users WHERE email = ?";
$stmt = $db->prepare($query);
$stmt->bindValue(1, $token_data['payload']['email']);
$stmt->execute();
$count = $stmt->rowCount();
if ($count > 0) {
header('Location: index.php');
} else {
$plus = new Google_Service_Plus( $client );
$me = $plus->people->get('me');
$query = "INSERT INTO users (name,email,role) VALUES(?,?,?)";
$stmt = $db->prepare($query);
$stmt->bindValue(1, $me['displayName']);
$stmt->bindValue(2, $token_data['payload']['email']);
$stmt->bindValue(3, 'regular');
$stmt->execute();
header('Location: index.php');
}
}
}
Specifically here
if($client->isAccessTokenExpired()) {
echo 'Access Token Expired'; // Debug
$client->authenticate;
$newAccessToken = json_decode($client->getAccessToken());
$client->refreshToken($newAccessToken->refresh_token);
}
Once my token expires, I cannot logout nor access any of the webpages as they require to have a valid token..
nor can i login, as that requires it too!
Or alternatively, can I just disable it!
EDIT
I'm very sorry, I'm tired and assuming everyone knows what I'm talking about.. The issue is that when the access token expires, I can either unset the $_SESSION['access_token'] and force relogging in ( major problem ) or have a way of just refreshing / disabling the token/expire so it won't impede on any ongoing processes for the user.
I would recommend reading a basic guide about OAuth so you can get the general idea.
Basically the server and the client go through a series of steps to prove that they are who they say they are. Once this has been completed the server will issue a short lived access_token and a refresh_token.
You can then use this access_token in all Api requests. However this access_token has a limited lifetime. When it expires you must give the refresh_token to the server and it will issue another access_token
To do this with the Google Api PHP library you use this code
//$client is the GApi Client
if($client->isAccessTokenExpired()) {
echo 'Access Token Expired'; // Debug
$client->refreshToken('your_refresh_token');
}

Saving Google Drive access Tokens for future calls

I have a PHP set of scripts using Google's Drive API and PHP examples, but I do not seem to be able to cache authorization requests...
<?php
echo 'This is a new request... setting parameters';
$drive_fileid=$_GET['drive_fileid'];
$drive_userid=$_GET['drive_userid'];
$drive_permission=$_GET['drive_permission'];
$_SESSION['drive_fileid']=$drive_fileid;
$_SESSION['drive_userid']=$drive_userid;
$_SESSION['drive_permission']=$drive_permission;
if($_SESSION['drive_fileid']==''){
echo 'Invalid drive file id. Aborting...';
exit;
} else $drive_fileid=$_SESSION['drive_fileid'];
if($_SESSION['drive_userid']==''){
echo 'Invalid drive user id. Aborting...';
exit;
} else $drive_userid=$_SESSION['drive_userid'];
if($_SESSION['drive_permission']==''){
echo 'Invalid drive permission. Aborting...';
exit;
} else $drive_permission=$_SESSION['drive_permission'];
// Now, if we have been through all this before, lets grab stored tokens...
// These never seem to work.
$getFormSQL="SELECT * from `users` where email='".$email."'";
$getFormData=mysql_query($getFormSQL) or die("Died trying to get auth token from the database with this user");
$formRow = mysql_fetch_array($getFormData);
$oauthToken=$formRow['driveoauth'];
$oauthAccessToken=$formRow['driveoauthaccess'];
require_once 'src/Google_Client.php';
require_once 'src/contrib/Google_DriveService.php';
$client = new Google_Client();
$client->setClientId('myappid.apps.googleusercontent.com');
$client->setClientSecret('myclientsecret');
$client->setRedirectUri('https://www.mywebsite.net/driveapi/oauth2callback');
$client->setScopes(array('https://www.googleapis.com/auth/drive'));
$service = new Google_DriveService($client);
$authUrl = $client->createAuthUrl();
// Since we have no token, we redirect the user to the Google Auth page...
if($oauthToken=='')header( 'Location: '.$authUrl ) ;
$authCode = trim($oauthToken);
// Try authenticate access token
try {
$client->setAccessToken($oauthAccessToken);
$authed=1;
} catch (Exception $e) {
echo '<P>Couldnt authenticate access token';
$authed=0;
}
// If that didn't work, lets generate a new one
if($authed==0){
try {
$accessToken = $client->authenticate($authCode);
$client->setAccessToken($accessToken);
} catch (Exception $e) {
header( 'Location: '.$authUrl ) ;
}
echo 'Got an access token: '.$accessToken;
// Save access token
$accessData=json_decode($accessToken,true);
echo '<P>Extracted and saved: '.$accessData['access_token'].'<P>';
$updateQuery ="UPDATE `users` ";
$updateQuery.=" set ";
$updateQuery.="driveoauthaccess='".$accessData['access_token']."'";
$updateQuery.=" where email='".$email."'";
mysql_query($updateQuery) or die("Unable to update database! ".mysql_error());
}
echo '<P><B>Existing permissions on the file/folder:</B><BR>';
$existingpermissions= $service->permissions->listPermissions($drive_fileid);
$existingpermissionarray=$existingpermissions['items'];
?>
Why am I not able to reuse the tokens I generate?

Categories