How do correctly authorise a Facebook App - facebook-apps

I am creating a basic Facebook app, and when a user without permission visits the app, they are redirected to the authorisation page. However, the page doesn't display, and I see the following error.
This content cannot be displayed in a frame
Opening it in a new window then shows the authorisation page for my app. Clicking 'Go to App' then takes me to the App, but in it's own window, away from Facebook. Going back to FB and reloding the App page now works.
Stranger yet, when I am logged out and go to my app page, I get a Facebook 404 page (4oh4.php).
I'm guessing that I am doing this wrong somehow, so can anyone see anything obvious wrong with my script? Thanks.
To see what is happening - http://apps.facebook.com/dyne_drewett_news/
<?php
require 'fb/facebook.php';
$fbconfig['appUrl'] = 'my-app-url'; // Create An instance of our Facebook Application.
$facebook = new Facebook(array(
'appId' => 'my-app-ID', // Entered correctly in actual script
'secret' => 'me-app-secret', // Entered correctly in actual script
'cookies' => 'true',
));
// Get the app User ID
$user = $facebook->getUser();
if($user) :
try{ // If the user has been authenticated then proceed
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e){
error_log($e);
$user = null;
}
endif;
// If the user is authenticated then generate the variable for the logout URL
if($user) :
$logoutUrl = $facebook->getLogoutUrl();
?>
<!-- My HTML goes here -->
<?php
else :
$loginUrl = $facebook->getLoginUrl();
header('Location: '.$loginUrl);
endif;
?>

Because you are working in an iframe, you'll have to execute JavaScript redirects. Only that way will you be able to redirect the top most frame -
echo "<script language=javascript>";
echo "top.location.href ='".$url."';";
echo "</script>";
exit();
This is the only way to do complete redirects within a Facebook application. Any other redirect (with PHP for example) will only redirect the user within the iframe...

Related

How to find user's email ID? - Google Oauth2 API PHP Client

I am implementing an Audio library manager which uses user's google drive as backend storage. I am using PHP (google-api-php-client-2.2.1) to get the user's authorization for accessing his/her google drive.
So far I am able to receive access token and refresh token using example code from google (https://developers.google.com/api-client-library/php/auth/web-app), and also tested by listing files of user's google drive.
However, I am not able to figure out programmatically which user has given authorization to my application. Just user's email address will do. I don't need any other information.
I am using the following code.
<?php
require_once 'google-api-php-client/vendor/autoload.php';
session_start();
$client = new Google_Client();
$client->setAuthConfig('client_secret.json'); //downloaded from google oauth credentials portal. It includes redirect URL
$client->setAccessType("offline"); // offline access
$client->setIncludeGrantedScopes(true); // incremental auth
$client->addScope(Google_Service_Drive::DRIVE_METADATA_READONLY);
if (! isset($_GET['code'])) {
//Get authorization and User consent from Google
$auth_url = $client->createAuthUrl();
header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
} else { //Authorization completed
//Get access token
$client->authenticate($_GET['code']);
$_SESSION['access_token'] = $client->getAccessToken();
$_SESSION['refresh_token'] = $client->getRefreshToken();
echo "Access Token<br>";
var_dump ($_SESSION['access_token']); //works
echo "<br>";
echo "Refresh Token<br>";
var_dump ($_SESSION['refresh_token']); //works
echo "<br>";
$service=new Google_Service_Oauth2($client);
echo "Auth2 Service created<br>"; //Getting this print
$usr_info=$service->userinfo;
echo "User Info<br>"; //Getting this print
var_dump ($usr_info); //Getting this print, Very long JSON structure. But info is mostly pertaining to my app...no user information showing here
echo "<br>";
//$usr_info_get = $usr_info->get(); //Throwing Error
//$usr_info_get = $usr_info->get(['email']); //Throwing Error
//$usr_info_get = $usr_info->get()['email']; //Throwing Error
echo "User Info Get<br>";
//var_dump ($usr_info_get);
echo "<br>";
}
?>
The class for userInfo is like this
class Google_Service_Oauth2_Resource_Userinfo extends Google_Service_Resource
{
/**
* (userinfo.get)
*
* #param array $optParams Optional parameters.
* #return Google_Service_Oauth2_Userinfoplus
*/
public function get($optParams = array())
{
$params = array();
$params = array_merge($params, $optParams);
return $this->call('get', array($params), "Google_Service_Oauth2_Userinfoplus");
}
}
The params for get() method should be optional, but
$userInfo->get()
also given me Server Error.
I am not finding anything else from my google search on this.
I tried this (6 year old thread) but code errors out (apiHttpRequest class not found)
How to identify a Google OAuth2 user?
I tried reading about openID but seems kinda complex. Also, not sure if google-api-php-client has helper class for openID.
I would really appreciate your help. Already spent 2+ days reading google api client php code but now up against the wall.

Session data not being saved on some mobile versions of Safari

It works just fine on my iPhone 3GS, but several employees with iPhone 4 and up are not able to log into my site through safari because their login credentials are not being saved to $_SESSION. If they download chrome onto their phones it works.
Any idea how to get this working?
When a user attempts to log in, their credentials are first verified as being accurate, and when they are they are sent to:
validate_login.php
<?php
session_start();
// sent from the login form
// employee id and username
$employeeId = $_POST['employee_id'];
$password = $_POST['password'];
//make connection to database, bail if no connection
$connection = odbc_pconnect('workorders','','');
if (!$connection) { exit("Connection Failed: " . $connection); }
//retrieve usernames and passwords
$sql = "SELECT * FROM LoginTable WHERE EmployeeID='$employeeId' and Password='$password'";
$rs = odbc_exec($connection, $sql);
if (!$rs) { exit("Error in SQL"); }
if(odbc_fetch_row($rs)) {
// register employeeId and password in session cookie and redirect to homepage
$_SESSION['employee_id'] = $employeeId;
header("location:../../home.php");
}
else {
header("location:../../login.php?error=0");
}
//close connection
odbc_close($connection);
?>
This is about as simple as you can be... any idea why it wouldn't be working? When I do a check at the top of every page that they are logged in:
<?php
session_start();
//validate user logged in; if not, redirect to login
if(!isset($_SESSION['employee_id'])){
header("location:login.php");
}
?>
It just thinks they're not logged in and throws them back out to login.php
Again, this is just an issue on Safari for newer iPhones as far as I can tell. Suggestions?

Facebook PHP SDK auth between main domain and multiple subdomains

I really don't manage to make this work. I've tried already all the steps I've found on SO or other websites, but my cross-domain fb authentication doesn't work..
How my auth script looks like:
session_set_cookie_params(0,"/",".my-domain.com");
session_start();
// include facebook class
try {
$fb = new Facebook(array(
'appId' => $facebook_app_id,
'secret' => $facebook_app_secret,
'cookie' => true
));
} catch(FacebookAPIException $e) {
// no active fb session
}
// other content here
try {
$uid = $fb->getUser();
if($uid) {
$user = $fb->api('/me','GET');
}
} catch(FacebookApiException $e) {
// not logged in
}
Now the problem is that this code works perfect on my-domain.com but not on subdomain.my-domain.com.
Even if I successfully authenticate on the main domain my-domain.com, when I'm visiting subdomain.my-domain.com the session of the main domain is replaced and the connection is lost.
Note that in the case of subdomain.my-domain.com there is no API Exception thrown but the $uid is 0.
I've already set the domain on FB APP Settings page as my-domain.com.
Which is the problem here?

How to store google api (OAuth 2) permissions?

i'm using the examples provided in the "google-api-php-client"-Library (http://code.google.com/p/google-api-php-client/) to implement user login and authorization on my website with google services.
I didn't make any changes to the examples, except adding my Client-ID, etc..
The authorization itself works fine: Users can login and i can fetch the provided informations.
However, when leaving the page, the whole authorization procedure is called again; users are not remembered and need to grant permissions again, which is some kind of annoying and not typical for google-logins as i know them.
For example: On stackoverflow, i'm logged in with my google account.
Whenever i revisit this site, i'm logged in automaticly, or (if logged out) just have to log in again - i do not have to confirm the general rights again.
Using the examples on my site however, forces the user to allow access whenever the site is visited again.
Did i make any mistakes, when using the examples?
What do i have to do, to avoid the permission request over and over again?
Thanks in advance for any kind of help!
Use this code for first time to retrieve access_code and save it to database:
<?php
require 'google-api-php-client/src/Google_Client.php';
require 'google-api-php-client/src/contrib/Google_DriveService.php';
require 'google-api-php-client/src/contrib/Google_Oauth2Service.php';
session_start();
$client = new Google_Client();
$client->setClientId(CLIENT_ID);
$client->setClientSecret(CLIENT_SECRET);
$client->setRedirectUri(REDIRECT_URI);
$client->setScopes(array(
'https://www.googleapis.com/auth/drive',
'https://www.googleapis.com/auth/userinfo.email',
'https://www.googleapis.com/auth/userinfo.profile'));
$client->setUseObjects(true);
$service = new Google_DriveService($client);
$client->authenticate();
$_SESSION['token'] = $client->getAccessToken();
const ACCESS_TOKEN=$_SESSION['token'];
//code here to save in database
?>
Once ACCESS_TOKEN is saved in database change code to:
<?php
require 'google-api-php-client/src/Google_Client.php';
require 'google-api-php-client/src/contrib/Google_DriveService.php';
require 'google-api-php-client/src/contrib/Google_Oauth2Service.php';
session_start();
$client = new Google_Client();
$client->setClientId(CLIENT_ID);
$client->setClientSecret(CLIENT_SECRET);
$client->setRedirectUri(REDIRECT_URI);
$client->setScopes(array(
'https://www.googleapis.com/auth/drive',
'https://www.googleapis.com/auth/userinfo.email',
'https://www.googleapis.com/auth/userinfo.profile'));
$client->setUseObjects(true);
$service = new Google_DriveService($client);
//ACCESS_TOKEN is already saved in database, is being saved on first time login.
$_SESSION['access_token'] = ACCESS_TOKEN;
if (isset($_SESSION['access_token'])) {
$client->setAccessToken($_SESSION['access_token']);
}
if ($client->getAccessToken())
{
$userinfo = $service->about->get();
echo '<script>console.log('.json_encode($userinfo).');</script>';
$userinfoService = new Google_OAuth2Service($client);
$user = $userinfoService->userinfo->get();
echo '<script>console.log('.json_encode($user).');</script>';
}
?>
That works fine for me.
Based on the kaushal's answer:
<?php
require_once 'globals.php';
require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_DriveService.php';
$client = new Google_Client();
// Get your credentials from the APIs Console
$client->setClientId('YOUR_ID');
$client->setClientSecret('YOUR_SECRET');
$client->setRedirectUri('REDIRECT_URI');
$client->setScopes(array('https://www.googleapis.com/auth/drive'));
$service = new Google_DriveService($client);
$client->setUseObjects(true);
//if no token in the session
if ($_SESSION['google_token'] == '') {
//get stored token from DB
$sToken = $oDb->getOne("SELECT `google_token` FROM `users` WHERE `u_id` = " . (int)$_SESSION['user_id']);
//if no stored token in DB
if ($sToken == '') {
//autentificate user
$client->authenticate();
//get new token
$token = $client->getAccessToken();
//set token in session
$_SESSION['google_token'] = $token;
// set token in DB
$oDb->Query("UPDATE `users` SET `google_token`='$token' WHERE `u_id` = " . (int)$_SESSION['user_id']);
} else {
$_SESSION['google_token'] = $sToken;
}
}
$client->setAccessToken($_SESSION['google_token']);
//do what you wanna do with clients drive here
?>
The Google Drive SDK documentation includes a complete PHP sample application that you can use as a reference to get started:
https://developers.google.com/drive/examples/php
Basically, once the user is logged in and you retrieve access token and refresh token, you store those credentials in a database and reuse them instead of asking the user to authenticate every time.

Page tab app, redirecting user back to restricted page on authentication

I can use the following code to redirect a user back to the page my app is installed on using the following code:
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $app_secret,
'cookie' => true
));
$signed_request = $facebook->getSignedRequest();
$page = $signed_request['page'];
$page_id = $page['id'];
$page_array = $facebook->api("/$page_id");
$page_link = $page_array['page_link'];
$redirect_uri = $page_link . '?sk=app_' . $app_id
$user = $facebook->getUser();
if(!$user) {
$url = $facebook->getLoginUrl(array('redirect_uri' => $redirect_uri));
echo "<script type='text/javascript'>top.location.href = '$url';</script>";
}
This works fine for most pages but if a page has age restrictions (and I cant guarantee all the pages using my app won't) the $facebook->api("/$page_id"); returns false because from what I can gather, I need the users access token in order to get this information which I can't get unless I authenticate them! Is there any way around this paradox or am I going to have to instruct my users not to age restrict their pages?
UPDATE
I realise I can simply redirect to facebook.com/$page_id which will take the user back to the page after authentication and would save me having to make the api request for $page_link but ideally I would like them to be redirected to my apps page tab on that page no matter what the specified default landing tab is.