Google Plus Login API not working on production server - api

I have implemented the google plus api on development server and it works fine. I used the same code on production server. But after requesting the permission it takes a long time to return to my site and login.
Can anyone please let me know what might be the cause. I have used oauth2.
Below is the code I am using
<?php
session_start();
require_once 'googleplus/src/Google_Client.php';
require_once 'googleplus/src/contrib/Google_Oauth2Service.php';
class Webpage_UserGPlusLogin extends Webpage
{
public function __construct()
{
$temp_redirect = $_SESSION['RETURN_URL_AFTERLOGIN'];
$this->title = 'User Account';
$client = new Google_Client();
$client->setApplicationName(WEBSITE_NAME);
$client->setClientId(GOOGLE_PLUS_CLIENT_ID); // Client Id
$client->setClientSecret(GOOGLE_PLUS_CLIENT_SECRET); // Client Secret
$client->setRedirectUri(GOOGLE_PLUS_REDIRECT_URI); // Redirect Uri set while creating API account
$client->setDeveloperKey(GOOGLE_PLUS_DEVELOPER_KEY); // Developer Key
$oauth2 = new Google_Oauth2Service($client);
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['token'] = $client->getAccessToken();
$redirect = GOOGLE_PLUS_REDIRECT_URI;
header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL)); // Redirects to same page
return;
}
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
if (isset($_REQUEST['logout'])) {
unset($_SESSION['token']);
$client->revokeToken();
}
if(!isset($_SESSION['email_address_user_account'])) // Check if user is already logged in or not
{
if ($client->getAccessToken()) {
$user = $oauth2->userinfo->get(); // Google API call to get current user information
$email = filter_var($user['email'], FILTER_SANITIZE_EMAIL);
$img = filter_var($user['picture'], FILTER_VALIDATE_URL);
$googleuserid = $user['id'];
$given_name = $user['given_name'];
$family_name = $user['family_name'];
// The access token may have been updated lazily.
$_SESSION['token'] = $client->getAccessToken();
// If email address is present in DB return user data else insert user info in DB
$this->result = UserAccount::gplus_sign_up($email, $googleuserid, $given_name, $family_name);
// Create new user object.
$this->user_account = new UserAccount($this->result['id'],$this->result['email_address'],$this->result['password'],$this->result['confirmation_code'],$this->result['is_confirmed'], $this->result['first_name'], $this->result['last_name']);
$_SESSION['gplus_email_address'] = $email;
$_SESSION['gplus_first_name'] = $given_name;
$_SESSION['gplus_last_name'] = $family_name;
$_SESSION['gplus_id'] = $googleuserid;
$_SESSION['gplus_profile_pic'] = $img;
$_SESSION['email_address_user_account'] = $email;
} else {
$authUrl = $client->createAuthUrl();
}
}
if(isset($temp_redirect))
header("Location:".$temp_redirect);
else
header("Location:/");
}
}
Thanks in advance

Try this
use following code
$temp = json_decode($_SESSION['token']);
$request = "https://www.googleapis.com/oauth2/v1/userinfo?alt=json";
$curl = curl_init();
curl_setopt($curl,CURLOPT_URL,$request);
curl_setopt($curl,CURLOPT_RETURNTRANSFER,1);
curl_setopt($curl,CURLOPT_TIMEOUT,30);
curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,false);
curl_setopt($curl, CURLINFO_HEADER_OUT, true);
curl_setopt($curl,CURLOPT_HTTPHEADER,array('Authorization: OAuth '.$temp->access_token));
$response = trim(curl_exec($curl));
$info = curl_getinfo($curl);
$request_header_info = curl_getinfo($curl, CURLINFO_HEADER_OUT);
//var_dump($info);
//var_dump($request_header_info);
curl_close($curl);
echo "<pre>";
print_r(json_decode($response));
instade of
$user = $oauth2->userinfo->get(); // Google API call to get current user information`enter code here`
Hope this will help you .. :)

Related

How to implement code for OAuth 2.0 Authorization for Google Directory API Without Command Line Interface

I have seen code in google directory api documentation for command line interface and have worked with it, the code works fine. But I want write code that runs without terminal and runs when on a page when the page is loaded because i have to run the code in the terminal every hour after it's expired, is there anyway i can get the code to run when i visit the page of authorization code.
The code work's with command-line interface, but i want it to work without command-line, what can i do?
Given Below is the code from Google Directory API and the URL:
URL : https://developers.google.com/admin-sdk/directory/v1/quickstart/php
<?php
require __DIR__ . '/vendor/autoload.php';
if (php_sapi_name() != 'cli') {
throw new Exception('This application must be run on the command line.');
}
/**
* Returns an authorized API client.
* #return Google_Client the authorized client object
*/
function getClient()
{
$client = new Google_Client();
$client->setApplicationName('G Suite Directory API PHP Quickstart');
$client->setScopes(Google_Service_Directory::ADMIN_DIRECTORY_USER_READONLY);
$client->setAuthConfig('credentials.json');
$client->setAccessType('offline');
$client->setPrompt('select_account consent');
// Load previously authorized token from a file, if it exists.
// The file token.json stores the user's access and refresh tokens, and is
// created automatically when the authorization flow completes for the first
// time.
$tokenPath = 'token.json';
if (file_exists($tokenPath)) {
$accessToken = json_decode(file_get_contents($tokenPath), true);
$client->setAccessToken($accessToken);
}
// If there is no previous token or it's expired.
if ($client->isAccessTokenExpired()) {
// Refresh the token if possible, else fetch a new one.
if ($client->getRefreshToken()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
} else {
// Request authorization from the user.
$authUrl = $client->createAuthUrl();
printf("Open the following link in your browser:\n%s\n", $authUrl);
print 'Enter verification code: ';
$authCode = trim(fgets(STDIN));
// Exchange authorization code for an access token.
$accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
$client->setAccessToken($accessToken);
// Check to see if there was an error.
if (array_key_exists('error', $accessToken)) {
throw new Exception(join(', ', $accessToken));
}
}
// Save the token to a file.
if (!file_exists(dirname($tokenPath))) {
mkdir(dirname($tokenPath), 0700, true);
}
file_put_contents($tokenPath, json_encode($client->getAccessToken()));
}
return $client;
}
// Get the API client and construct the service object.
$client = getClient();
$service = new Google_Service_Directory($client);
// Print the first 10 users in the domain.
$optParams = array(
'customer' => 'my_customer',
'maxResults' => 10,
'orderBy' => 'email',
);
$results = $service->users->listUsers($optParams);
if (count($results->getUsers()) == 0) {
print "No users found.\n";
} else {
print "Users:\n";
foreach ($results->getUsers() as $user) {
printf("%s (%s)\n", $user->getPrimaryEmail(),
$user->getName()->getFullName());
}
}
I have also tried to implement the code from OAuth 2.0 for Web Server Applications in wordpress page with the template but it's not working, which is from https://developers.google.com/identity/protocols/oauth2/web-server#php_1
and this is my code:
<?php
require __DIR__ . '/vendor/autoload.php';
session_start();
/**
* Returns an authorized API client.
* #return Google_Client the authorized client object
*/
$client = new Google_Client();
$client->setApplicationName('G Suite Directory API PHP Quickstart');
$client->addScope(Google_Service_Directory::ADMIN_DIRECTORY_USER);
$client->setAuthConfig('/path/to/credentials.json');
$client->setAccessType('offline');
$client->setApprovalPrompt("consent");
$client->setIncludeGrantedScopes(true); // incremental auth
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
$client->setAccessToken($_SESSION['access_token']);
$service = new Google_Service_Directory($client);
} else {
$redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/oauth2callback.php';
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}

Google oAuth not working after 3600 seconds

I'm using google oAuth for getting youtube latest streaming. It works for 3600 seconds. But then it stopped working. After some researching at stackoverflow, many people wrote to use "SetAccessType": "offline" .
I did it but same result.
Here is my snippet.
<?php
/**
* Library Requirements
*
* 1. Install composer (https://getcomposer.org)
* 2. On the command line, change to this directory (api-samples/php)
* 3. Require the google/apiclient library
* $ composer require google/apiclient:~2.0
*/
$stream_id = "";
if (!file_exists(__DIR__ . '/vendor/autoload.php')) {
throw new \Exception('please run "composer require google/apiclient:~2.0" in "' . __DIR__ .'"');
}
require_once __DIR__ . '/vendor/autoload.php';
session_start();
$OAUTH2_CLIENT_ID = '972289696318-q037nr25oti8gs5h7hcj5lfkl7erklh6.apps.googleusercontent.com';
$OAUTH2_CLIENT_SECRET = 'cbmQyfeXWGb93RkN7KSHLQKB';
$client = new Google_Client();
$client->setAccessType('online');
$client->setClientId($OAUTH2_CLIENT_ID);
//$client->setExpires_in('10000000');
$client->setClientSecret($OAUTH2_CLIENT_SECRET);
$client->setScopes('https://www.googleapis.com/auth/youtube');
$redirect = filter_var('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'],
FILTER_SANITIZE_URL);
$client->setRedirectUri($redirect);
// Define an object that will be used to make all API requests.
$youtube = new Google_Service_YouTube($client);
//print_r($youtube);
// Check if an auth token exists for the required scopes
$tokenSessionKey = 'token-' . $client->prepareScopes();
if (isset($_GET['code'])) {
if (strval($_SESSION['state']) !== strval($_GET['state'])) {
die('The session state did not match.');
}
$client->authenticate($_GET['code']);
$_SESSION[$tokenSessionKey] = $client->getAccessToken();
header('Location: ' . $redirect);
}
if (isset($_SESSION[$tokenSessionKey])) {
$client->setAccessToken($_SESSION[$tokenSessionKey]);
}
/*
if ($client->isAccessTokenExpired()) {
$refreshToken = $client->getRefreshToken();
//print_r($refreshToken);
// $client->refreshToken($refreshToken);
$newAccessToken = $client->getAccessToken();
$newAccessToken['refresh_token'] = $refreshToken;
file_put_contents($credentialsPath, json_encode($newAccessToken));
}
*/
// Check to ensure that the access token was successfully acquired.
if ($client->getAccessToken()) {
try {
// Execute an API request that lists broadcasts owned by the user who
// authorized the request.
//print_r($youtube);
$broadcastsResponse = $youtube->liveBroadcasts->listLiveBroadcasts(
'id,snippet',
array(
'mine' => 'true',
));
//print_r($broadcastsResponse);
$htmlBody .= "<h3>Live Broadcasts</h3><ul>";
$count = 0;
foreach ($broadcastsResponse['items'] as $broadcastItem) {
// print_r($count+1);
$count = $count+1;
if($count == 1) {
$htmlBody .= sprintf('<li>%s (%s)</li>', $broadcastItem['snippet']['title'],
$broadcastItem['id']);
$stream_id = $broadcastItem['id'];
}
// print_r($broadcastItem);
}
$htmlBody .= '</ul>';
} catch (Google_Service_Exception $e) {
$htmlBody = sprintf('<p>A service error occurred: <code>%s</code></p>',
htmlspecialchars($e->getMessage()));
} catch (Google_Exception $e) {
$htmlBody = sprintf('<p>An client error occurred: <code>%s</code></p>',
htmlspecialchars($e->getMessage()));
}
$_SESSION[$tokenSessionKey] = $client->getAccessToken();
} elseif ($OAUTH2_CLIENT_ID == 'Replace_me') {
$htmlBody = <<<END
<h3>Client Credentials Required</h3>
<p>
You need to set <code>\$OAUTH2_CLIENT_ID</code> and
<code>\$OAUTH2_CLIENT_ID</code> before proceeding.
<p>
END;
} 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 = <<<END
<h3>Authorization Required</h3>
<p>You need to authorize access before proceeding.<p>
END;
}
?>
<!doctype html>
<html>
<head>
<title>My Live Broadcasts</title>
</head>
<body>
<?php echo $stream_id; ?>
</body>
</html>
Any idea what can i do?
NB: My purpose is, any one can authenticate here and can get latest youtube streaming id. But I'm struct with oAuth after 3600 seconds.
:(
Your Access Token has an expiry time. The expiry usually is half an hour (1800 seconds), although this can vary. The value is set by the Authentication Server. The expiry time is sent to you along with the Access Token.
After the Access Token expires, the server will no longer accept it. You must request a new one using your Refresh Token. You should have gotten it along with the first Access Token.
If you do not have a Refresh Token, you'll have to log in again.

Magento: listing products from API

This is my script I have used from Magento Reference (see: RequestToken Retrieve the list of products for Admin user with OAuth authentication)
I am submiting this script from my localhost.
/**
* Example of retrieving the products list using Admin account via Magento REST API. OAuth authorization is used
* Preconditions:
* 1. Install php oauth extension
* 2. If you were authorized as a Customer before this step, clear browser cookies for 'yourhost'
* 3. Create at least one product in Magento
* 4. Configure resource permissions for Admin REST user for retrieving all product data for Admin
* 5. Create a Consumer
*/
// $callbackUrl is a path to your file with OAuth authentication example for the Admin user
$callbackUrl = "http://yourhost/oauth_admin.php";
$temporaryCredentialsRequestUrl = "http://yourhost/oauth/initiate?oauth_callback=" . urlencode($callbackUrl);
$adminAuthorizationUrl = 'http://yourhost/admin/oAuth_authorize';
$accessTokenRequestUrl = 'http://yourhost/oauth/token';
$apiUrl = 'http://yourhost/api/rest';
$consumerKey = 'yourconsumerkey';
$consumerSecret = 'yourconsumersecret';
session_start();
if (!isset($_GET['oauth_token']) && isset($_SESSION['state']) && $_SESSION['state'] == 1) {
$_SESSION['state'] = 0;
}
try {
$authType = ($_SESSION['state'] == 2) ? OAUTH_AUTH_TYPE_AUTHORIZATION : OAUTH_AUTH_TYPE_URI;
$oauthClient = new OAuth($consumerKey, $consumerSecret, OAUTH_SIG_METHOD_HMACSHA1, $authType);
$oauthClient->enableDebug();
if (!isset($_GET['oauth_token']) && !$_SESSION['state']) {
$requestToken = $oauthClient->getRequestToken($temporaryCredentialsRequestUrl);
$_SESSION['secret'] = $requestToken['oauth_token_secret'];
$_SESSION['state'] = 1;
header('Location: ' . $adminAuthorizationUrl . '?oauth_token=' . $requestToken['oauth_token']);
exit;
} else if ($_SESSION['state'] == 1) {
$oauthClient->setToken($_GET['oauth_token'], $_SESSION['secret']);
$accessToken = $oauthClient->getAccessToken($accessTokenRequestUrl);
$_SESSION['state'] = 2;
$_SESSION['token'] = $accessToken['oauth_token'];
$_SESSION['secret'] = $accessToken['oauth_token_secret'];
header('Location: ' . $callbackUrl);
exit;
} else {
$oauthClient->setToken($_SESSION['token'], $_SESSION['secret']);
$resourceUrl = "$apiUrl/products";
$oauthClient->fetch($resourceUrl, array(), 'GET', array('Content-Type' => 'application/json'));
$productsList = json_decode($oauthClient->getLastResponse());
print_r($productsList);
}
} catch (OAuthException $e) {
print_r($e->getMessage());
echo "<br/>";
print_r($e->lastResponse);
}
As a result I am getting "Whoops, our bad..." page, I was expecting to see list of products.
In the URL I am seeing oauth_token.
http://myUrl/oAuth_authorize?oauth_token=a4315776966dca4fa5d3786f4fghjkab157cf
Can somebody point me out what to do next? If you need any additional data, please ask.
There is a typo in url
$adminAuthorizationUrl = 'http://yourhost/admin/oAuth_authorize';
should be
$adminAuthorizationUrl = 'http://yourhost/admin/oauth_authorize';

ZF2 - init or something that is called in every module controller

I have a Module called "Backend" and in this module I want to check for valid authentication on all pages except the backend_login page. How do I do this? I tried to add it to the onBootstrap in the Backend/Module.php , but it turns out that is called in my other modules as well... which is of course not what I want.
So how do I do this?
Thanks in advance!
To get clear information about zf2 authentication you can follow:
ZF2 authentication
adapter auth
database table auth
LDAP auth
digest auth....These all are different methods here is an example of database table auth:
in every controller's action, where you need user auth something should like this:
use Zend\Authentication\Result;
use Zend\Authentication\AuthenticationService;
use Zend\Authentication\Adapter\AdapterInterface;
use Zend\Db\Adapter\Adapter as DbAdapter;
use Zend\Authentication\Adapter\DbTable as AuthAdapter;
public function login($credential)
{
$bcrypt = new Bcrypt();
$user = new User();
$auth = new AuthenticationService();
$user->exchangeArray($credential);
$password = $user->password;
$data = $this->getUserTable()->selectUser($user->username);
if (!$data){
$message = 'Username or password is not correct!';
}
elseif($auth->getIdentity() == $user->username){
$message = 'You have already logged in';
}
elseif($bcrypt->verify($password, $data->password)){
$sm = $this->getServiceLocator();
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$authAdapter = new AuthAdapter(
$dbAdapter,
'user',
'username',
'password'
);
$authAdapter -> setIdentity($user->username) -> setCredential($data->password);
$result = $auth->authenticate($authAdapter);
$message = "Login succesfull.Welcome ".$result->getIdentity();
} else {
$message = 'Username or password is not correct';
}
return new ViewModel(array("message" =>$message));
}
Like this in every action you can check whether it is authenticated or not
if($auth -> hasIdentity()){
//your stuff
}
else{
//redirected to your login route;
}
I had once a similar problem and figured it out within my Module.php in the onBootstrap() function. Try this, it worked for me:
class Module {
// white list to access with being non-authenticated
//the list may contain action names, controller names as well as route names
protected $whitelist = array('login');
//....
public function onBootstrap($e){
$app = $e->getApplication();
$em = $app->getEventManager();
$sm = $app->getServiceManager();
$list = $this->whitelist;
$auth = new AuthenticationService();
$em->attach(MvcEvent::EVENT_ROUTE, function($e) use ($list, $auth) {
$match = $e->getRouteMatch();
// No route match, this is a 404
if (!$match instanceof RouteMatch) {
return;
}
// Route is whitelisted
$action = $match->getParam('action');
if (in_array($action, $list) ) {
return;
}
// User is authenticated
if ($auth->hasIdentity()){
return;
}
// the user isn't authenticated
// redirect to the user login page, as an example
$router = $e->getRouter();
$url = $router->assemble(array(
'controller' => 'auth',
'action'=>'login'
), array(
'name' => 'route_name',
));
$response = $e->getResponse();
$response->getHeaders()->addHeaderLine('Location', $url);
$response->setStatusCode(302);
return $response;
}, -100);
}
}
Or you may see bjyauthorize.

Joomla onUserAuthenticate

In the Joomla source, I found a method caled onUserAuthenticate, which could not be found in the API (through google), but its functionality is the similar to onLoginUser... So, after login/password check I need to run some more code via this function. As a result, I have true/false - depending on it I need to set users' authorization completely. Even if the user's login/password is correct, but my code returns false -> authorization fail...
I am trying something like:
functionon UserAuthenticate($credentials,$options,&$response){
jimport('joomla.user.helper');
$username=mysql_real_escape_string($credentials['username']);
$password=mysql_real_escape_string(md5($credentials['password']));
//my code returns $result
if($result!=NULL){
$response->status=JAUTHENTICATE_STATUS_SUCCESS;
$response->error_message='';
}
else{
$response->status=JAUTHENTICATE_STATUS_FAILURE;
$response->error_message=JText::_('JGLOBAL_AUTH_INVALID_PASS');
}
}
onUserAuthenticate is an event not a method. You use plugins to listen for Joomla events, in this case usually a user plugin would listen for this. When the event happens your code will run.
http://docs.joomla.org/Plugin
You can try this for custom login form-
$app = JFactory::getApplication();
$data = array();
$data['return'] = '';
$data['username'] = JRequest::getVar('username', '', 'method', 'username');
$data['password'] = JRequest::getString('password', '', 'post', JREQUEST_ALLOWRAW);
// Get the log in options.
$options = array();
// Get the log in credentials.
$credentials = array();
$credentials['username'] = $data['username'];
$credentials['password'] = $data['password'];
// Perform the log in.
$error = $app->login($credentials, $options);
if (!JError::isError($error)) {
$response->status=JAUTHENTICATE_STATUS_SUCCESS;
$response->error_message='';
}else{
$response->status=JAUTHENTICATE_STATUS_FAILURE;
$response->error_message=JText::_('JGLOBAL_AUTH_INVALID_PASS');
}
If you want authenticate solution on function "onUserAuthenticate" you should check it yourself if user credential is valid or not And you do it with this code :
function onUserAuthenticate($credentials, $options, &$response)
{
$response->type = 'Joomla';
// Joomla does not like blank passwords
if (empty($credentials['password'])) {
$response->status = JAuthentication::STATUS_FAILURE;
$response->error_message = JText::_('JGLOBAL_AUTH_EMPTY_PASS_NOT_ALLOWED');
return false;
}
// Initialise variables.
$conditions = '';
// Get a database object
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select('id, password');
$query->from('#__users');
$query->where('username=' . $db->Quote($credentials['username']));
$db->setQuery($query);
$result = $db->loadObject();
if ($result) {
$parts = explode(':', $result->password);
$crypt = $parts[0];
$salt = #$parts[1];
$testcrypt = JUserHelper::getCryptedPassword($credentials['password'], $salt);
if ($crypt == $testcrypt) {
$user = JUser::getInstance($result->id); // Bring this in line with the rest of the system
$response->email = $user->email;
$response->fullname = $user->name;
$response->status = JAuthentication::STATUS_SUCCESS;
$response->error_message = '';
print_r("You login correct Sir");
die();
} else {
print_r("you enter wrong credential");
die();
$response->status = JAuthentication::STATUS_FAILURE;
$response->error_message = JText::_('JGLOBAL_AUTH_INVALID_PASS');
}
} else {
print_r("you enter blank credential");
die();
$response->status = JAuthentication::STATUS_FAILURE;
$response->error_message = JText::_('JGLOBAL_AUTH_NO_USER');
}
return true;
}