I have used the following code to authenticate a user (it is based off of googles examples of a services account on github):
<?php
//API INFORMATION
$client_id='xx-x.apps.googleusercontent.com';
$client_email='xx-xx#developer.gserviceaccount.com';
$client_key='xx';
$cert_loc='directory/google-api-bushbase-privatekey.p12';
//SET THE APP SCROPES
$scopes=array(
'https://www.googleapis.com/auth/plus.login',
'https://www.googleapis.com/auth/plus.me',
'https://www.googleapis.com/auth/userinfo.email',
'https://www.googleapis.com/auth/userinfo.profile'
);
//GET ASSERTION CREDENTIALS
if(($key=file_get_contents($cert_loc))!==false){
//GOT GOOGLE CERTIFICATE
try{
$auth= new Google_Auth_AssertionCredentials($client_email,$scopes,$key);
}catch (Exception $e){
echo $error;
echo 'Unable to get authenticate with Google servers</div>';
//RETURN FALSE
return false;
}
}else{
echo $error;
echo 'Unable to get Google certificate</div>';
//RETURN FALSE
return false;
}
//GOOGLE CONNECTION OBJECT
try {
$connection = new Google_Client();
$connection->setApplicationName("Bush Base");
$connection->setAssertionCredentials($auth);
//CHECK TO SEE IF TOKEN IS EXPIRED VIA SESSION
if (isset($_SESSION['service_token'])) {
$connection->setAccessToken($_SESSION['service_token']);
}
if($connection->getAuth()->isAccessTokenExpired()){
//TOKEN IS EXPIRED SO RESET WITH ASSERTION CRED
$connection->getAuth()->refreshTokenWithAssertion($auth);
}
//GET THE TOKEN VALUE
$_SESSION['service_token']=$connection->getAccessToken();
$connection->setAccessToken($_SESSION['service_token']);
//THE CONNECTION WAS NOT SUCCESSFUL
}catch (Exception $e){
echo $error;
echo 'Unable to connect with Google database</div>';
//RETURN FALSE
return false;
}
//CREATE THE NEW GOOGLE SERVICES OBJECT
try{
$info =new Google_Service_Plus($connection);
}catch (Exception $e){
echo $error;
echo 'Unable to conntect to google services</div>';
//RETURN FALSE
return false;
}
try{
//GET THE USER INFO
$data= $info->people->get('me');
echo "<pre>";
print_r($data);
echo "</pre>";
}
I am trying to get the information for the user account 103283326808099970387 but some how i am authenticated as user 111631880133159328429.
If i go to https://plus.google.com/111631880133159328429, I get a 404 error.
Related
index.php() //plugin
`if (!isset($_GET['code']) || !isset($_SESSION['oauth2state'])) {
// If we don't have an authorization code then get one
$authUrl = $provider->getAuthorizationUrl();
$_SESSION['oauth2state'] = $provider->getState();
header('Location: ' . $authUrl);
exit;
//Check given state against previously stored one to mitigate CSRF attack
}
elseif (empty($_GET['state']) || ($_GET['state'] !== $_SESSION['oauth2state'])) {
unset($_SESSION['oauth2state']);
exit('Invalid state, make sure HTTP sessions are enabled.');
}
else {
// Try to get an access token (using the authorization coe grant)
try {
$token = $provider->getAccessToken('authorization_code', [
'code' => $_GET['code']
]);
// $token = $provider->getAccessToken('refresh_token', ['refresh_token' => $token->getRefreshToken()]);
// echo $token->getRefreshToken();
// print_r($token);
} catch (Exception $e) {
// echo 'tttttttttttttttttt';
exit('Failed to get access token: ' . $e->getMessage());
}
// Optional: Now you have a token you can look up a users profile data
try {
// We got an access token, let's now get the user's details
$user = $provider->getResourceOwner($token);
// print_r($user);
// Use these details to create a new profile
// printf('Hello %s!', $user->getName());
} catch (Exception $e) {
exit('Failed to get resource owner: ' . $e->getMessage());
}
// Use this to interact with an API on the users behalf
// echo $token->getToken();
}`
using this plugins finally i have getting token that stored user information but problem in where i am adding this tokent in my yii2 project for authentication of user and how the plugins skip the login page of our yii2 projects and directly enter in website without showing login page of our project....
I use Facebook SDK 5 with an index.php and a profile.php(only for presentation the data). I use them for log in in my website with facebook account, but after the first time that someone logs in from my computer to his fb account I don't have the option to log in again. I automatically log in with his account. How can I delete the "past user data"? I've tried deleting the session but nothing happened.
session_start();
unset($_SESSION['facebook_access_token']);
unset($accesstoken);
if (isset($accesstoken)){
echo hi;
try
{
$fbuid = $fb->getUser();
$me = $fb->api('/me');
}
catch(FacebookApiException $e){}
}
$helper = $fb->getRedirectLoginHelper();
$permissions = ['email']; // optional
try {
if (isset($_SESSION['facebook_access_token'])) {
$accessToken = $_SESSION['facebook_access_token'];
} else {
$accessToken = $helper->getAccessToken();
}
} catch(Facebook\Exceptions\facebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
if (isset($accessToken)) {
if (isset($_SESSION['facebook_access_token'])) {
$fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
}
else {
// getting short-lived access token
$_SESSION['facebook_access_token'] = (string) $accessToken;
// OAuth 2.0 client handler
$oAuth2Client = $fb->getOAuth2Client();
// Exchanges a short-lived access token for a long-lived one
$longLivedAccessToken = $oAuth2Client->getLongLivedAccessToken($_SESSION['facebook_access_token']);
$_SESSION['facebook_access_token'] = (string) $longLivedAccessToken;
// setting default access token to be used in script
$fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
}
// redirect the user to the profile page if it has "code" GET variable
if (isset($_GET['code'])) {
echo hi3;
header('Location: profile.php');
}
// getting basic info about user
try {
$profile_request = $fb->get('/me?fields=name,first_name,last_name,email');
$requestPicture = $fb->get('/me/picture?redirect=false&height=200'); //getting user picture
$picture = $requestPicture->getGraphUser();
$profile = $profile_request->getGraphUser();
$fbid = $profile->getProperty('id'); // To Get Facebook ID
$fbfullname = $profile->getProperty('name'); // To Get Facebook full name
$fbemail = $profile->getProperty('email'); // To Get Facebook email
$fbpic = "<img src='".$picture['url']."' class='img-rounded'/>";
# save the user nformation in session variable
$_SESSION['fb_id'] = $fbid.'</br>';
$_SESSION['fb_name'] = $fbfullname.'</br>';
$_SESSION['fb_email'] = $fbemail.'</br>';
$_SESSION['fb_pic'] = $fbpic.'</br>';
} catch(Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
session_destroy();
// redirecting user back to app login page
header("Location: ./");
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
} else {
// replace your website URL same as added in the developers.Facebook.com/apps e.g. if you used http instead of https and you used
$loginUrl = $helper->getLoginUrl('http://newpage.photoclub-tey.com.cy/please/', $permissions);
echo 'Log in with Facebook!';
}
unset($_SESSION);
unset($_SESSION['facebook_access_token']);
$accessToken->revokeToken();
session_destroy();
?>
I am trying to retrieve a new access token with my refresh token. Before I run a script to retrieve a new access token I want to check if my access token is still valid.
I am trying to do this with exceptions:
try
{
// Connect
$session = new SoapClient("../webservices/session.asmx?wsdl", array('trace' => 1));
$result = $session->AccessTokenLogon($accessTokenparams);
}
catch (SoapFault $e)
{
// Check if AcccessToken returns TokenInvalid
if ($result->AccessTokenLogonResult == "TokenInvalid")
{
// AccessToken is not valid anymore
// ..
// Run script to get new access token
// ..
// $_SESSION["access_token"] = $access_token;
}
else
{
// AccessToken is valid
echo "AccessToken is valid";
}
}
finally
{
// Run script with valid AccessToken
global $result, $session;
$cluster = $result->cluster;
$qq = new domDocument();
$qq->loadXML($session->__getLastResponse());
$newurl = $cluster . '/webservices/processxml.asmx?wsdl';
try
{
$client = new SoapClient($newurl);
$header = new SoapHeader('http://www.website.com/', 'Header', array('AccessToken' =>$_SESSION["access_token"]));
}
catch (SoapFault $e)
{
echo $e->getMessage();
}
try
{
echo '<br /><br />XML Result:<br /><br />';
$xml = ""; // XML request
$result = $client->__soapCall('ProcessXmlString', array(array('xmlRequest'=>$xml)), null, $header);
}
catch (SoapFault $e)
{
echo $e->getMessage();
}
}
With a valid access token the script is working. The XML request is posted to the webservice.
The script is not working when the accesstoken is not valid anymore. The script stores the new accesstoken in the session: $_SESSION["access_token"] = $access_token; but is not running the 'finally' part after retrieving a new accesstoken.
Does someone know how I can fix this and run the 'finally' after retrieving a new accesstoken?
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?
I have been Googling this for going on hours now. I have followed the Hello Analytics tutorial.
The application runs fine until the user has granted permission from the Google 'consent screen' at which point i receive the following error:
There wan a general error : Error calling GET My url
(403) Access Not Configured. Please use Google Developers Console to
activate the API for your project.
I have checked in the developer console and Analytics API is enabled and, after reading other posts on this, have added Google+ and Drive access.
NOTE: I am running this application locally and redirecting the redirecting back to 127.0.0.1.
I have added my code below for reference although I think the issue is to do with my google console account and / or running this application locally.
Appreciate any help with this guys. Please let me know if any further information is required.
==================================================================================
// --------------------- Google libraries
require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_AnalyticsService.php';
session_start();
// --------------------- Application credentials
$client = new Google_Client();
$client->setApplicationName('Interim Testing Tool');
$client->setClientId('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com');
$client->setClientSecret('xxxxxxxxxxxxxxxxxxxxxxxx');
$client->setRedirectUri('http://127.0.0.1');
$client->setDeveloperKey('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx');
$client->setScopes(array('https://www.googleapis.com/auth/analytics.readonly'));
// Returns objects from the Analytics Service instead of associative arrays.
$client->setUseObjects(true);
// --------------------- Client access checks
// Handle authorization flow from the server
if (isset($_GET['code'])) {
$client->authenticate();
$_SESSION['token'] = $client->getAccessToken();
$redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}
// Retrieve and use stored credentials if set
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
if (!$client->getAccessToken()) {
// CLient not logged in create a connect button
$authUrl = $client->createAuthUrl();
print "<a class='login' href='$authUrl'>Connect Me!</a>";
} else {
$analytics = new Google_AnalyticsService($client);
runMainDemo($analytics);
}
//-------------------------------------------------------------- Run main demo
function runMainDemo($analytics) {
try {
// Get the user's first view (profile) ID.
$profileId = getFirstProfileId($analytics);
if (isset($profileId)) {
// Query the Core Reporting API.
$results = getResults($analytics, $profileId);
// Output the results.
printResults($results);
}
} catch (apiServiceException $e) {
// Error from the API.
print 'There was an API error : ' . $e->getCode() . ' : ' . $e->getMessage();
} catch (Exception $e) {
print 'There wan a general error : ' . $e->getMessage();
}
}
// ------------------------------------------------------------------ Get first profile id
function getFirstprofileId($analytics) {
$accounts = $analytics->management_accounts->listManagementAccounts();
if (count($accounts->getItems()) > 0) {
$items = $accounts->getItems();
$firstAccountId = $items[0]->getId();
$webproperties = $analytics->management_webproperties->listManagementWebproperties($firstAccountId);
if (count($webproperties->getItems()) > 0) {
$items = $webproperties->getItems();
$firstWebpropertyId = $items[0]->getId();
$profiles = $analytics->management_profiles->listManagementProfiles($firstAccountId, $firstWebpropertyId);
if (count($profiles->getItems()) > 0) {
$items = $profiles->getItems();
return $items[0]->getId();
} else {
throw new Exception('No views (profiles) found for this user.');
}
} else {
throw new Exception('No webproperties found for this user.');
}
} else {
throw new Exception('No accounts found for this user.');
}
}