Using Codenvy to OAuth Google with php - php

I am fairly new to codenvy and php but I have doublechecked the following, yet I am still not asked to oauth into google when I launch this with the following code. I followed instructions from here. any obvious mistakes in the below?
https://developers.google.com/analytics/solutions/articles/hello-analytics-api
<?php
require_once 'src/Google/Client.php';
require_once 'src/Google/Service/Analytics.php';
session_start();
$client = new Google_Client();
$client->setApplicationName('Hello Analytics API Sample');
// Visit https://console.developers.google.com/ to generate your
// client id, client secret, and to register your redirect uri.
$client->setClientId('CONFIRMED THIS IS CORRECT');
$client->setClientSecret('CONFIRMED THIS IS CORRECT');
$client->setRedirectUri('https://codenvycorp.com/api/oauth/callback');
$client->setDeveloperKey('CONFIRMED THIS IS CORRECT');
$client->setScopes(array('https://www.googleapis.com/auth/analytics.readonly'));
// Magic. Returns objects from the Analytics Service instead of associative arrays.
$client->setUseObjects(true);
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));
}
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
if (!$client->getAccessToken()) {
$authUrl = $client->createAuthUrl();
print "<a class='login' href='$authUrl'>Connect Me!</a>";
} else {
$analytics = new apiAnalyticsService($client);
runMainDemo($analytics);
}
echo 'Hello World 321';
?>

If your project is public, please, share it with Codenvy's factory feature. So everyone will be able to look what is wrong with OAuth integration.
(You can access factory on left panel of the IDE)

Related

How to style for <a href> for php

<?php
echo "<a href='".$client->createAuthUrl()."'><button>Login with Google</button></a>";
?>
Im trying to add class for <a href> inside php echo , but i cant do any style what i want to do
<?php
echo "<a href='".$client->createAuthUrl()."'><button>Login with Google</button></a>";
?>
You can try something like this, I hope it will help you.
Login with Google"
Your use of single quotes and double quotes is a little mixed up. I should also add that buttons inside a tags aren't really correct. I'd suggest removing the button and styling the a tag instead. With that in mind, here are the options:
Regular CSS method
echo '<a class="mylink" href="'.$client->createAuthUrl().'">Login with Google</a>';
then in the stylesheet:
a.mylink{
styles here
}
Inline styling Method
echo '<a style="styles here" href="'.$client->createAuthUrl().'">Login with Google</a>';
From a google development stand point im going to ask why are you doing it like that? Just redirect the user using the location header if you can detect they aren't logged in.
index.php
login
login.php
$Auth = new Oauth2Authentication();
$client = $Auth->GetClient();
$client = $Auth->initializeClient($client);
relevant code from my Oauth2Authentication class.
function initializeClient($client)
{
try {
// Set the refresh token on the client.
if (isset($_SESSION['refresh_token']) && $_SESSION['refresh_token']) {
$client->refreshToken($_SESSION['refresh_token']);
}
// If the user has already authorized this app then get an access token
// else redirect to ask the user to authorize access to Google Analytics.
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
// Set the access token on the client.
$client->setAccessToken($_SESSION['access_token']);
// Refresh the access token if it's expired.
if ($client->isAccessTokenExpired()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
$client->setAccessToken($client->getAccessToken());
$_SESSION['access_token'] = $client->getAccessToken();
}
return $client;
} else {
// We do not have access request access.
header('Location: ' . filter_var( $client->getRedirectUri(), FILTER_SANITIZE_URL));
}
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
}
oauthcallback.php
<?php
require_once __DIR__. '/../vendor/autoload.php';
require_once __DIR__ . '/Oauth2Authentication.php';
// Start a session to persist credentials.
session_start();
// Handle authorization flow from the server.
if (!isset($_GET['code'])) {
// Request authorization of the user by displaying the consent screen
$Auth = new Oauth2Authentication();
$client = $Auth->GetClient();
$auth_url = $client->createAuthUrl();
header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
} else {
// Exchange the Authorization code for an access token and refresh token.
$Auth = new Oauth2Authentication();
$client = $Auth->GetClient();
$client->fetchAccessTokenWithAuthCode($_GET['code']); // Exchange the authentication code for a refresh token and access token.
// Add access token and refresh token to session.
$_SESSION['access_token'] = $client->getAccessToken();
$_SESSION['refresh_token'] = $client->getRefreshToken();
//Redirect back to main script
$redirect_uri = str_replace("oauth2callback.php","login.php", $client->getRedirectUri());
//header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
header('Location: http://localhost');
}

G Suite OpenId connection for personnal web application

I want to implement OpenId of G Suite api to connect the user of my own php application and use the G Suite manage of user.
So I have write the example below :
in index.php I have load autoload.php (with google-api-php-client library)
$client = new \Google_Client();
$client->setClientId(CLIENT_ID);
$client->setClientSecret(SECRET);
$client->setAuthConfig(ROOT_PATH.CLIENT_SECRET_JSON_FILE);
$client->setAccessType("offline");
$client->setIncludeGrantedScopes(true);
$client->setHostedDomain('mydomain.com');
$client->addScope(\Google_Service_Oauth2::USERINFO_PROFILE);
$redirect = $_SERVER['HTTP_HOST'];
$redirect = 'myapplication.mydomain.com';
$client->setRedirectUri('https://' . $redirect . '/oauth2callback.php');
$auth_url = $client->createAuthUrl();
header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
oauth2callback.php
$client = new \Google_Client();
$client->setClientId(CLIENT_ID);
$client->setClientSecret(SECRET);
$client->setAuthConfig(ROOT_PATH.CLIENT_SECRET_JSON_FILE);
$client->setRedirectUri('https://myapplication.mydomain.com/oauth2callback.php');
$client->setAccessType("offline");
$client->setIncludeGrantedScopes(true);
$client->setHostedDomain('mydomain.com');
if (!isset($_GET['code'])) {
$auth_url = $client->createAuthUrl();
header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
}
else {
$client->fetchAccessTokenWithAuthCode($_GET['code']);
$_SESSION['access_token'] = $client->getAccessToken();
$oauth = new \Google_Service_Oauth2($client);
var_dump($oauth->userinfo->get());
}
exit();
All is ok with this example, but, I can connect on my application with another account of my G Suite domain :-(
I don't understand where I must configure it to authorize only the user of my G Suite domain to access at my application.
Can you help me ?
Thanks
I have a start of answer, it's impossible.
But, with the return of api, it's possible to check the value hd (hosted domain) to compare it with my. https://developers.google.com/identity/sign-in/web/backend-auth
In my case, I haven't return value of hd :-( and I don't why
I have found the solution :-)
It's simple. The scope must be "email". If there is this value, Gsuite return automatically value in hd to check it.
After the return, I juste test the value to compare with my Gsuite domain :-)

Google API :OAuth 2.0 authenticate return "invalid_grand" "Bad request"

I am using code examples of YouTube Api v3
I turned on YouTube Data API v3.
I create Oauth Client in the developer console
I added my url ($app->url('google.auth.test')) to allowed redirect URI
I copied the client id and secret
Then I used example code
$client = new Google_Client();
$client->setClientId($OAUTH2_CLIENT_ID);
$client->setClientSecret($OAUTH2_CLIENT_SECRET);
$client->setApprovalPrompt('force');//read some topics - it could help
$client->setAccessType('offline');//read some topics - it could help
$client->setScopes('https://www.googleapis.com/auth/youtube');
$redirect = filter_var($app->url('google.auth.test'),
FILTER_SANITIZE_URL);//uri of this page
$client->setRedirectUri($redirect);
// Define an object that will be used to make all API requests.
$youtube = new Google_Service_YouTube($client);
if (isset($_GET['code'])) {
if (strval($_SESSION['state']) !== strval($_GET['state'])) {
die('The session state did not match.');
}
$cred = $client->authenticate($_GET['code']);
dump($_GET['code']);
dump($cred);
dump($client->getAccessToken());
exit;
$_SESSION['token'] = $client->getAccessToken();
header('Location: ' . $redirect);
}
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
// Check to ensure that the access token was successfully acquired.
if ($client->getAccessToken()) {
// This code creates a new, private playlist in the authorized user's
//some code
$_SESSION['token'] = $client->getAccessToken();
} else {
// If the user hasn't authorized the app, initiate the OAuth flow
$state = mt_rand();
$client->setState($state);
$_SESSION['state'] = $state;
$authUrl = $client->createAuthUrl();
$htmlBody = "
<h3>Authorization Required</h3>
<p>You need to authorize access before proceeding.<p>
";
return $htmlBody;
}
After I go to to $app-url('google.auth.test')
I am being redirected to
Authorization Required
You need to authorize access before proceeding.
It is OK.
After clicking - redirect to google auth it is OK.
Accept google auth and redirect back to $app-url('google.auth.test')
I get code and my status in get request, but $client->authenticate($_GET['code']); return me error
Dump info:
I think I did not find some advanced google settings.
Thanks for answers!

Google API and OAuth 2.0

I'm trying to use google calendar API with php library and i'm facing issues on the authentification of the user to the google api.
I have a question. I've seen some come where you had to set the Api key / developer key to the Google_Client object with the method setDeveloperKey(), but i've also seen some people who don't. Could someone explain to me what difference does it make ?
The thing i'd like to do is to connect a user who have a google account to my application so he can add, list, remove, etc, events from a calendar. This is what i'm doing for the moment for the authentification :
$client = new Google_Client();
$client->setApplicationName("Test GCAL");
$client->setClientId($clientid);
$client->setClientSecret($clientsecret);
$client->setRedirectUri($callback_url);
$client->setAccessType("offline");
$client->setApprovalPrompt("force");
$client->setScopes("https://www.googleapis.com/auth/calendar");
$service = new Google_Service_Calendar($client);
Am i doing it right ?
Does someone have a working commented code that i can analyse ? I can't find one that's working on the internet.. Or maybe a tutorial that explain everything about google api and oauth stuff. I'm so confused about tokens and nobody seems to use refresh tokens, and to me that's essential.. But maybe i'm wrong ?
Thanks for your answers
I don't think you NEED to use setDeveloperKey I suspect that its only used for public APIs to enable you to use them but I haven't really tested it or thought about it before. I will have to look into that a bit more.
This is the code I use for connecting to Google Calendar with Oauth2. ripped directly from the Accessing Google Calendar with PHP – Oauth2 tutorial
<?php
require_once 'Google/Client.php';
require_once 'Google/Service/Calendar.php';
require_once 'CalendarHelper.php';
session_start();
$client = new Google_Client();
$client->setApplicationName("Client_Library_Examples");
$client->setDeveloperKey("AIzaSyBBH88dIQPjcl5nIG-n1mmuQ12J7HThDBE");
$client->setClientId('2046123799103-i6cjd1hkjntu5bkdkjj5cdnpcu4iju8p.apps.googleusercontent.com');
$client->setClientSecret('6s4YOx3upyJhtwnetovfK40e');
$client->setRedirectUri('http://localhost/google-api-php-client-samples/Calendar/oauth2Pure.php');
$client->setAccessType('offline'); // Gets us our refreshtoken
$client->setScopes(array('https://www.googleapis.com/auth/calendar.readonly'));
//For loging out.
if (isset($_GET['logout'])) {
unset($_SESSION['token']);
}
// Step 2: The user accepted your access now you need to exchange it.
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['token'] = $client->getAccessToken();
$redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}
// Step 1: The user has not authenticated we give them a link to login
if (!isset($_SESSION['token'])) {
$authUrl = $client->createAuthUrl();
print "<a class='login' href='$authUrl'>Connect Me!</a>";
}
// Step 3: We have access we can now create our service
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
print "<a class='logout' href='".$_SERVER['PHP_SELF']."?logout=1'>LogOut</a><br>";
$service = new Google_Service_Calendar($client);
$calendarList = $service->calendarList->listCalendarList();;
print_r($calendarList);
while(true) {
foreach ($calendarList->getItems() as $calendarListEntry) {
echo $calendarListEntry->getSummary()."<br>\n";
}
$pageToken = $calendarList->getNextPageToken();
if ($pageToken) {
$optParams = array('pageToken' => $pageToken);
$calendarList = $service->calendarList->listCalendarList($optParams);
} else {
break;
}
}
}
?>

Insert Moment in Google+ using Google PHP Client

I'm trying to insert some activity app in a Google+ profile as shown in this documentation page:
https://developers.google.com/+/api/latest/moments/insert
I successfully obtain the access token needed, but seems the moments->insert method doesn't make anything.
If successful I would expect to see something on this page, once made the access, but nothing happen
https://plus.google.com/u/0/apps/activities
That's my code
<?php
require_once '../google-api-php-client/Google_Client.php';
require_once '../google-api-php-client/contrib/Google_PlusService.php';
session_start();
$client = new Google_Client();
$client->setClientId('xxxxxxxxxxxx-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com');
$client->setClientSecret('xxxxxxxxxxxxxxxxxxxxxxxx');
$client->setRedirectUri('http://www.myregisteredcallbackurl.com');
$client->setAccessType('offline');
$client->setScopes(array('https://www.googleapis.com/auth/plus.login'));
$client->setApprovalPrompt('force');
$plus = new Google_PlusService($client);
if (isset($_GET['logout'])) {
unset($_SESSION['token']);
}
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['token'] = $client->getAccessToken();
header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
}
if (isset($_SESSION['token'])) {
echo 'Logout<br><br>'.PHP_EOL.PHP_EOL;
$client->setAccessToken($_SESSION['token']);
$moment = new Google_Moment();
$moment->setType('http://schemas.google.com/AddActivity');
$itemScope = new Google_ItemScope();
$itemScope->setUrl('https://developers.google.com/+/plugins/snippet/examples/thing');
$moment->setTarget($itemScope);
$plus->moments->insert('me', 'vault', $moment);
}
if ($client->getAccessToken()) {
$_SESSION['token'] = $client->getAccessToken();
} else {
$authUrl = $client->createAuthUrl();
echo 'Connect<br>';
}
You need to add the requestvisibleactions permissions to your scope. The easiest way to do this is to switch from the conventional OAuth 2.0 flow to the new Google+ Sign-In flow - the Google+ team provides a PHP sample for Google+ Sign-In. If you want to continue using the older OAuth flow, you need to append request_visible_actions=[the app activity types] to your authorization URL.
Related questions:
Google+ PHP moments not working
Google+ Insert moment using dot-net-client
Google+ unable to insert moment
In your code, you are really close, the following seems to work for me:
$client = new Google_Client();
$client->setClientId('YOUR_CLIENT_ID');
$client->setClientSecret('YOUR_CLIENT_SECRET');
$client->setRedirectUri('http://example.com/callback.php');
$client->setAccessType('offline');
$client->setScopes(array('https://www.googleapis.com/auth/plus.login'));
$client->setRequestVisibleActions(array('https://schemas.google.com/AddActivity'));
$plus = new Google_PlusService($client);
To check the app activities that you have written, visit the app activity log.

Categories