Zend Gmail Oauth: How to get authenticated user profile? - zend-framework

I am using Zend Gmail Oauth 1.0 for implementing login with Gmail feature.
After successful authentication, how can I get authenticated user's profile, specifically user's unique gmail id? Here is the code:
$THREE_LEGGED_SCOPES = array('https://mail.google.com/',
'https://www.google.com/m8/feeds');
$options = array(
'requestScheme' => Zend_Oauth::REQUEST_SCHEME_HEADER,
'version' => '1.0',
'consumerKey' => $THREE_LEGGED_CONSUMER_KEY,
'consumerSecret' => $THREE_LEGGED_CONSUMER_SECRET_HMAC,
'callbackUrl' => getCurrentUrl(),
'requestTokenUrl' => 'https://www.google.com/accounts/OAuthGetRequestToken',
'userAuthorizationUrl' => 'https://www.google.com/accounts/OAuthAuthorizeToken',
'accessTokenUrl' => 'https://www.google.com/accounts/OAuthGetAccessToken'
);
if ($THREE_LEGGED_SIGNATURE_METHOD == 'RSA-SHA1') {
$options['signatureMethod'] = 'RSA-SHA1';
$options['consumerSecret'] = new Zend_Crypt_Rsa_Key_Private(
file_get_contents(realpath($THREE_LEGGED_RSA_PRIVATE_KEY)));
} else {
$options['signatureMethod'] = 'HMAC-SHA1';
$options['consumerSecret'] = $THREE_LEGGED_CONSUMER_SECRET_HMAC;
}
$consumer = new Zend_Oauth_Consumer($options);
/**
* When using HMAC-SHA1, you need to persist the request token in some way.
* This is because you'll need the request token's token secret when upgrading
* to an access token later on. The example below saves the token object
* as a session variable.
*/
if (!isset($_SESSION['ACCESS_TOKEN'])) {
if (!isset($_SESSION['REQUEST_TOKEN'])) {
// Get Request Token and redirect to Google
$_SESSION['REQUEST_TOKEN'] = serialize($consumer->getRequestToken(array('scope' => implode(' ', $THREE_LEGGED_SCOPES))));
$consumer->redirect();
} else {
// Have Request Token already, Get Access Token
$_SESSION['ACCESS_TOKEN'] = serialize($consumer->getAccessToken($_GET, unserialize($_SESSION['REQUEST_TOKEN'])));
header('Location: ' . getCurrentUrl(false));
exit;
}
} else {
// Retrieve mail using Access Token
$accessToken = unserialize($_SESSION['ACCESS_TOKEN']);
}

near as I can tell you can't.
Gmail doesn't have an api just a read only feed.
However if you want that feed the scope url is:
https://mail.google.com/mail/feed/atom/
There are some api's for working with gmail accounts in the context of Google Apps.

Related

Error pulling companies user is admin of in LinkedIn

I'm currently trying to pull the list of company pages a user is the admin of with the LinkedIn API and am getting the following response:
Array
(
[response] => {
"errorCode": 0,
"message": "Member does not have permission to get companies as admin.",
"requestId": "R1LHP32UKD",
"status": 403,
"timestamp": 1482357250945
}
[http_code] => 403
)
The call works perfectly when authenticated as the same user in the LinkedIn API Console.
Has anyone else come across this?
I figured out the problem.
Even though I had made sure the app had the rw_company_admin permission checked off, I wasn't passing that in the scope when requesting oath2 authorization.
My fixed code below:
The call:
return $linkedin->getAuthorizationUrl("r_basicprofile w_share rw_company_admin", $thisurl);
The function:
public function getAuthorizationUrl($scope, $callback)
{
$params = array('response_type' => 'code',
'client_id' => $this->api_key,
'scope' => $scope,
'state' => uniqid('', true), // unique long string
'redirect_uri' => $callback,
);
// Authentication request
$url = 'https://www.linkedin.com/uas/oauth2/authorization?' . http_build_query($params);
// Needed to identify request when it returns to us
$_SESSION['Linkedin_state'] = $params['state'];
$_SESSION['Linkedin_callback'] = $callback;
// this is where to send the user
return $url;
}
First you have to get user token of linkedin user
Use Socialite or REST API package for oauth.
Once you having user token it is pretty simple to fetch Company list under admin user
$token = 'uflefjefheilhfbwrfliehbwfeklfw'; // user token
$api_url = "https://api.linkedin.com/v1/companies?oauth2_access_token=".$token."&format=json&is-company-admin=true";
$pages = json_decode(file_get_contents($api_url));
You have get $pages json array of list of company profile.

How to integrate Google login on a CakePHP REST API

I am building an Android app that is interfaced with a CakePHP 3 web API. Since a RESTful API cannot rely on cookies, I understand that I need JSON web tokens (JWT) to make this happen, and would much prefer to use a google login. I already got the Android side to request a token from Google's API, but now I am lost on how to incorporate this into my API for authentication.
I've searched around for some tutorials, such as this one: http://blog.jainsiddharth21.com/2013/04/29/login-with-google-in-cakephp/, but it relies on session data. I'm building the API in CakePHP 3, so I've looked at some of the plugins, such as ADmad/JwtAuth, so maybe I could extend on this to allow google authentication, but I am not sure how.
Login With Gmail and Specific email address to allowed to login in CakePHP 3.x
Composer to install
"google/apiclient": "^2.0"
Required gmail with login
https://console.developers.google.com/apis/credentials?project=mdpms-187410&organizationId=1095988912954
Create project and create secret key and client id
Project in set name and redirect URL
NOTE:- redirect URL must be .com and .org domain
If you develop in local machine then create follow type of virtual host
example.com and example.org
Virtual host create then
Follow this step:
Set configuration file in app_globle.php
'Google' =>
[
'googleClientID' => '123456.apps.googleusercontent.com',
'googleClientSecret' => 'abcdefghi',
'googleRedirectUrl' => 'http://example.com/oauth2callback'
]
Gmail login route
//Google login
$routes->connect('/account/google-login', ['controller' => 'Account', 'action' => 'googlelogin'], ['_name' => 'account-google-login']);
$routes->connect('/oauth2callback', ['controller' => 'Account', 'action' => 'confirmlogin'], ['_name' => 'account-google-redirect-url']);
Google login action code:
/**
* Gmail login method
*/
public function googlelogin()
{
$client = new Google_Client();
$client->setClientId(Configure::read('Google.googleClientID'));
$client->setClientSecret(Configure::read('Google.googleClientSecret'));
$client->setRedirectUri(Configure::read('Google.googleRedirectUrl'));
$client->se
tScopes([
"https://www.googleapis.com/auth/userinfo.profile",
'https://www.googleapis.com/auth/userinfo.email'
]);
$url = $client->createAuthUrl();
$this->redirect($url);
}
Google redirect url Action
/**
* Gmail auth redirect action
* #return type gmail auth data
*/
public function confirmlogin()
{
$client = new Google_Client();
$client->setClientId(Configure::read('Google.googleClientID'));
$client->setClientSecret(Configure::read('Google.googleClientSecret'));
$client->setRedirectUri(Configure::read('Google.googleRedirectUrl'));
$client->setScopes([
"https://www.googleapis.com/auth/userinfo.profile",
'https://www.googleapis.com/auth/userinfo.email'
]);
$client->setApprovalPrompt('auto');
$usersTable = TableRegistry::get('Users');
if (isset($this->request->query['code'])) {
$client->authenticate($this->request->query['code']);
$this->request->Session()->write('access_token', $client->getAccessToken());
}
if ($this->request->Session()->check('access_token') && ($this->request->Session()->read('access_token'))) {
$client->setAccessToken($this->request->Session()->read('access_token'));
}
if ($client->getAccessToken()) {
$this->request->Session()->write('access_token', $client->getAccessToken());
$oauth2 = new Google_Service_Oauth2($client);
$user = $oauth2->userinfo->get();
try {
if (!empty($user)) {
if ((preg_match("/(#example\.com)$/", $user['email'])) || (preg_match("/(#example\.in)$/", $user['email']))) {
$result = $usersTable->find('all')
->where(['email' => $user['email']])
->first();
if (!empty($result)) {
$this->AccessControl->setUser($result->toArray(), false);
$this->Flash->set(__('You have successfuly logged in.'), ['element' => 'success']);
$this->redirect(['_name' => 'dashboard']);
} else {
$data = [];
$data['email'] = $user['email'];
$data['first_name'] = $user['givenName'];
$data['last_name'] = $user['familyName'];
$data['socialId'] = $user['id'];
$data['role_id'] = Configure::read('Role.loginWithGmailUserRole');
//$data matches my Users table
$entity = $usersTable->newEntity($data);
if ($usersTable->save($entity)) {
$data['id'] = $entity->id;
$this->AccessControl->setUser($data, false);
$this->Flash->set(__('You have successfuly logged in.'), ['element' => 'success']);
$this->redirect(['_name' => 'dashboard']);
} else {
$this->Flash->error(__('Invalid login.'));
//redirect to login action
$this->redirect(['_name' => 'account-login']);
}
}
} else {
$this->Flash->error(__('Your email is invalid for this application.'));
//redirect to login action
$this->redirect(['_name' => 'account-login']);
}
} else {
$this->Flash->error(__('Gmail infos not found.'));
//redirect to login action
return $this->redirect(['_name' => 'account-login']);
}
} catch (\Exception $e) {
$this->Flash->error(__('Gmail error.'));
return $this->redirect(['_name' => 'account-login']);
}
}
}

how can I get a facebook Page access token from a users access token using php?

I am trying to get a page access token starting out with just a users access token stored in my database and a page id. So far I have not been using the facebook.php instead just using php's curl_* functions. So far I can send posts to the page (with a hard coded page id) but I want to impersonate the page when doing so.
Can I do this easily without facebook.php, that would be nice as it might save me from feeling like I should rewrite what I've done so far. If not, then how would I get the page access token from the facebook object - remember so far at least I don't store user ids or page ids in my db, just user access tokens and of course my app id and secret.
I've been looking at the example for getting page access tokens but I find it not quite what I need as it gets a user object and in so doing seems to force the user to login to facebook each time, but I stored the user access token to avoid exactly that from happening.
Do I need more permissions than manage_page and publish_stream? I tried adding offline_access but it doesn't seem available anymore (roadmap mentions this).
here is some of my code from my most recent attempt which uses the facebook.php file:
// try using facebook.php
require_once 'src/facebook.php';
// Create our Application instance
$facebook = new Facebook(array(
'appId' => $FB_APP_ID, // $FB_APP_ID hardcoded earlier
'secret' => $FB_APP_SECRET, // $FB_APP_SECRET hardcoded earlier
));
$facebook->setAccessToken($FB_ACCESS_TOKEN );
//got user access token $FB_ACCESS_TOKEN from database
// Get User ID -- why?
$user = $facebook->getUser();
//------ get PAGE access token
$attachment_1 = array(
'access_token' => $FB_ACCESS_TOKEN
);
$result = $facebook->api("/me/accounts", $attachment_1);
foreach($result["data"] as $page) {
if($page["id"] == $page_id) {// $page_id hardcoded earlier
$page_access_token = $page["access_token"];
break;
}
}
echo '<br/>'.__FILE__.' '.__FUNCTION__.' '.__LINE__.' $result= ' ;
var_dump($result); //this prints: array(1) { ["data"]=> array(0) { } }
$facebook->setAccessToken($page_access_token );
// Get User ID, why - re-init with new token maybe?
$user = $facebook->getUser();
//------ write to page wall
try {
$attachment = array(
'access_token' => $page_access_token,
'link' => $postLink,
'message'=> $postMessage
);
$result = $facebook->api('/me/feed','POST', $attachment);
echo '<br/>'.__FILE__.' '.__FUNCTION__.' '.__LINE__.' $result= ' ;
var_dump($result);
} catch(Exception $e) {
echo '<br/>'.__FILE__.' '.__FUNCTION__.' '.__LINE__.' $e= ' ;
var_dump($e); /*this gives : "An active access token must
be used to query information about the
current user." */
}
die;
Thanks
PS: I hardcoded the user id and started calling
$result = $facebook->api("/$user_id/accounts", $attachment_1);
and I still get an empty result.
PPS: The Graph API Explorer does not show my fan pages either even though my account is set as the Manager. My attempts to post work but show as being from my account rather than from the page.
PPPS: made a little progress by adding permissions on the graph explorer page to get an access token that way but that doesn't help as I need to the the access token programmatically. When a user with many fan pages logs in to my site I want to show them the list of their facebook fan pages to choose from. In practice aren't the permissions just granted on the app?
PPPPS: the list of permissions on my app now stands at : email, user_about_me, publish_actions
and
Extended Permissions:
manage_pages, publish_stream, create_note, status_update, share_item
do I need more? when I try now I still fail to get anything from the call to:
$facebook->api("/$user_id/accounts", $attachment_1);
Px5S: DOH!!! I see now that I was neglecting to add the manage_pages permissions to my call for a user access token when my scripts first get one and store it in the DB. But when I reuse that new access token I still get the error : "An active access token must be used to query information about the current user." So, can't such tokens be reused? Aren't they long term? will read more stuff...
Here is my functioning code, still messy but seems to work, note the scopes on the first $dialog_url, and please feel free to mock my code or even suggest improvements :
function doWallPost($postName='',$postMessage='',$postLink='',$postCaption='',$postDescription=''){
global $FB_APP_ID, $FB_APP_SECRET;
$APP_RETURN_URL=((substr($_SERVER['SERVER_PROTOCOL'],0,4)=="HTTP")?"http://":"https://").$_SERVER['HTTP_HOST'].$_SERVER['SCRIPT_NAME'].'?returnurl=1';
$code = $_REQUEST["code"];
$FB_ACCESS_TOKEN = getFaceBookAccessToken( );
$FB_ACCESS_TOKEN_OLD = $FB_ACCESS_TOKEN;
//if no code ot facebook access token get one
if( empty($code) && empty($FB_ACCESS_TOKEN) && $_REQUEST["returnurl"] != '1')
{
// if( $_REQUEST["returnurl"] == '1') die;
$dialog_url = "http://www.facebook.com/dialog/oauth?client_id=".$FB_APP_ID."&redirect_uri=".$APP_RETURN_URL."&scope=publish_stream,manage_pages";
header("Location:$dialog_url");
}
if( empty($FB_ACCESS_TOKEN) ){
if($_REQUEST['error_code'] == '200'){
return null;
}else if (!empty($code)){
$token_url = "https://graph.facebook.com/oauth/access_token?client_id=".$FB_APP_ID."&redirect_uri=".urlencode($APP_RETURN_URL)."&client_secret=".$FB_APP_SECRET."&code=".$code;
$access_token = file_get_contents($token_url);
$param1=explode("&",$access_token);
$param2=explode("=",$param1[0]);
$FB_ACCESS_TOKEN=$param2[1];
}else{
return null;
}
}
if(!empty($FB_ACCESS_TOKEN) && $FB_ACCESS_TOKEN_OLD != $FB_ACCESS_TOKEN) {
setFaceBookAccessToken( $FB_ACCESS_TOKEN);
}
$_SESSION['FB_ACCESS_TOKEN'] = $FB_ACCESS_TOKEN;
$page_name = '';
$page_id = getFaceBookPageId(); //from db
if(empty($page_id ) ) return null;
//in case there are multiple page_ids separated by commas
if(stripos($page_id, ',') !== false ){
$page_ids = explode(',', $page_id) ;// = substr($page_id, 0, stripos($page_id, ','));
}
$result = null;
foreach($page_ids as $page_id){
$page_id = trim($page_id);
if( !empty($FB_ACCESS_TOKEN)){
//get page_id
require_once 'src/facebook.php';
// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
'appId' => $FB_APP_ID,
'secret' => $FB_APP_SECRET
));
$facebook->setAccessToken($FB_ACCESS_TOKEN );
//------ get PAGE access token
$page_access_token ='';
$attachment_1 = array(
'access_token' => $FB_ACCESS_TOKEN
);
$result = $facebook->api("/me/accounts", $attachment_1);
if(count($result["data"])==0) {
return null;
}
foreach($result["data"] as $page) {
if($page["id"] == $page_id) {
$page_access_token = $page["access_token"];
break;
}
}
//------ write to page wall
try {
$attachment = array(
'access_token' => $page_access_token,
'link' => $postLink,
'message'=> $postMessage
);
$result = $facebook->api('/me/feed','POST', $attachment);
} catch(Exception $e) {
return null;
}
} //end if( !empty($FB_ACCESS_TOKEN))
}//end foreach
return $result; }
Now, I wonder if I can send the same message to several pages at once ...
Yup, just by looping over the ids, see above, it now supports multiple page ids.
And unless someone wants to contribute to the code - there's lots of ways it can be improved - I'm done.

How to publish photos on behalf of the user with application access token ? (not with user access token)

I want my application to publish photos, user has already registered my app with publish_stream permission and is currently disconnected from facebook.
Documentation https://developers.facebook.com/docs/publishing/ said :
To publish a 'photo' object you need
a valid access token
publish_stream permission
I tried a HTTP POST request :
https://graph.facebook.com/<USER_ID>/photos?access_token=<APPLICATION_ACCESS_TOKEN>
POST param : "url":"<link_to_some_picture>"
And i got an exception :
content={"error":{"message":"A user access token is required to request this resource.","type":"OAuthException","code":102}}
To publish photos on behalf of user i cannot pass a user access token... Why i can post links but not photos with my application access token?
Your title states that you are using an application access token - the error you are getting clearly states the problem. You need a user access token.
You'll need to extend your users access token in order to perform actions on his/her behalf when they are not connected to Facebook.
Here is a good resource for information about dealing with expired tokens and how to refresh them -
https://developers.facebook.com/docs/authentication/access-token-expiration/
When user registered your application then you can store the user's user access token after you can used that access token to post on behalf of user.When user come to your application next time you can update that access token.
You can use following function to get extended access token:
public function getExtendedAccessToken(){
try {
// need to circumvent json_decode by calling _oauthRequest
// directly, since response isn't JSON format.
$access_token_response =
$this->_oauthRequest(
$this->getUrl('graph', '/oauth/access_token'),
$params = array( 'client_id' => $this->getAppId(),
'client_secret' => $this->getApiSecret(),
'grant_type'=>'fb_exchange_token',
'fb_exchange_token'=>$this->getAccessToken(),
));
} catch (FacebookApiException $e) {
// most likely that user very recently revoked authorization.
// In any event, we don't have an access token, so say so.
return false;
}
if (empty($access_token_response)) {
return false;
}
$response_params = array();
parse_str($access_token_response, $response_params);
if (!isset($response_params['access_token'])) {
return false;
}
return $response_params['access_token'];
}
$fid = $row[1];
echo "fid = $fid\n";
$message =$row[2];
echo "msg = $message\n";
$friends = $facebook->api("/$user/friends?fields=id");
$args= array(
'app_id' => $facebook->getAppId(),
'to' => $fid,
'link' => 'http://www.facebook.com',
'message'=>$message,
);
$post_id = $facebook->api('/fid /feed', 'POST', $args);
var_dump($post_id);

Facebook request access token and get email

I have a facebook login script for my site that currently works fine. I want to add the ability to request the email from user, along with the current basic info. I know i need to request an access token, but icant quite figure out how. Here's my current code:
$facebook = new Facebook(array(
'appId' => APP_ID,
'secret' => APP_SECRET,
'cookie' => true
));
$session = $facebook->getSession();
if (!empty($session)) {
# Active session, let's try getting the user id (getUser()) and user info (api->('/me'))
try {
$uid = $facebook->getUser();
$user = $facebook->api('/me/');
You have to provide an extended permission for email at the time of login..
$access_token = $this->facebook->getAccessToken();
//check permissions list
$permissions_list = $this->facebook->api('/me/permissions', 'GET', array('access_token' => $access_token));
$permissions_needed = array('email');
foreach ($permissions_needed as $perm) {
if (!isset($permissions_list['data'][0][$perm]) || $permissions_list['data'][0][$perm] != 1) {
$login = $facebook->getLoginUrl(array('scope' => 'email,user_birthday',
'redirect_uri' => your site redirectUri,
'display' => 'popup'
));
header("location:$login");
}
}
$user = $facebook->getUser();
if ($user) {
try {
$userInfo = $facebook->api("/$user");
} catch (FacebookApiException $e) {
echo $e->getMessage();
}
}
print_r($userInfo);
Have a look at the server-side authentication process - this is where you pass through the permissions you want (known as "scope"). The user will be presented with a login panel if they are not already logged in, and then afterwards a separate permissions panel for any permissions above basic you are requesting and that they haven't already granted. You will then receive an auth token or a code that can be exchanged for a token, and you use this to then further query the user and get their email details in the response.
Good luck!