FacebookJavaScriptLoginHelper fails to authenticate user on first page refresh - facebook

I'm creating a Facebook app for mobile devices. Such application is displayed within a mobile browser, unlike Facebook canvas pages which are held in an iframe.
I'm using a mix of JS and PHP SDK to authorize and authenticate a user. The user needs to be already logged into Facebook to use my app. If not, they need to log in with Facebook login button. As a bridge between JS and PHP SDKs I'm using FacebookJavaScriptLoginHelper.
Part of my Facebook.php library doing the job:
<?php
// Initialize the SDK
FacebookSession::setDefaultApplication($this->app_id, $this->app_secret);
// Create the login helper
$this->helper = new FacebookJavaScriptLoginHelper();
try {
$this->session = $this->helper->getSession();
} catch(FacebookRequestException $ex) {
// When Facebook returns an error
} catch(Exception $ex) {
// When validation fails or other local issues
}
if ($this->session) {
// User logged in
$this->session = new FacebookSession($this->session->getToken());
}
?>
Facebook JS init:
<script type="text/javascript">
window.fbAsyncInit = function() {
FB.init({
appId: '{my app id}',
status: true,
xfbml: true,
cookie: true
});
}
FB.getLoginStatus(function(response) {
console.dir(response);
});
</script>
The above code works fine but there's a specific case when it fails. Let's assume I have two tabs open in my browser: in the first tab I have my app open, in the second one - I'm logged into Facebook. Two scenarios can take place:
I log out of Facebook and refresh the tab with my app. The result is correct:
FacebookSession is NULL
response.status from FB.getLoginStatus is 'unknown'. The user is not
logged in.
I go to the second tab, log back into Facebook and refresh the first tab with my app. The result is incorrect, but only on the first refresh:
FacebookSession is still NULL, even if
response.status of FB.getLoginStatus is 'connected'
The reason behind this fail on first refresh seems to be obvious: In the moment of reloading the page PHP SDK is triggered before Facebook cookie is refreshed. However, it's never a problem when the user logs out - in this case, somehow FacebookSession is updated instantly, as expected.
How come it does not work the same when the user logs into Facebook?

Does this help?
Subsequent calls to FB.getLoginStatus will return data from this cached response. This can cause problems where the user has logged into (or out of) Facebook since the last full session lookup, or if the user has removed your application in their account settings.
To get around this, you call FB.getLoginStatus with the second parameter set to true to force a roundtrip to Facebook - effectively refreshing the cache of the response object.
FB.getLoginStatus(function(response) {
// this will be called when the roundtrip to Facebook has completed
}, true);
Source: https://developers.facebook.com/docs/reference/javascript/FB.getLoginStatus
Section: Roundtrips to Facebook's servers

Related

Why does FB.getLoginStatus() return response status 'unknown' even though I'm logged into Facebook and FB.logout() has not been called?

We are developing a website at www.bodecanada.com. One of the login methods we provide is facebook. We also try to keep track of whether the user is logged into facebook or not when refreshing the page or opening the site in a new tab. We do this by calling FB.getLoginStatus() (from the Facebook js sdk). However, we are finding that in a few cases--for example, when opening the site in a new tab in Safari--the response status that comes back from FB.getLoginStatus is 'unknown'. The Facebook SDK documentation says this about the 'unknown' status:
FB.getLoginStatus() allows you to determine if a user is logged in to
Facebook and has authenticated your app. There are three possible
states for a user:
The user is logged into Facebook and has authorized your application. (connected)
The user is logged into Facebook but has not authorized your application.(not_authorized)
The user is either not logged into Facebook or explicitly logged out of your application so it doesn't attempt to connect to Facebook
and thus, we don't know if they've authenticated your application or
not. (unknown)
We are dealing with #3 in this case. However, when I visit facebook, I find I am not logged out. But at the same time, I am not "explicitly logged out" (meaning FB.logout() is called) from my site. So why is it returning 'unknown'?
One solution I found on google says to add cookies: true to FB.init() in order to enable 3rd party cookies, so I did so:
FB.init({
appId : process.env.FB_APP_ID,
cookie : true,
xfbml : true,
version : 'v2.2'
});
But this doesn't change anything.
So why does FB.getLoginStatus() return 'unknown' for the response status when I open the site in a new tab?
Thanks.
I had the same issue when I closed and reopened the browser again. What I did is put the fb.login function if the status is unknown. But, emergent windows must be enabled in the browser:
function statusChangeCallback(response) {
if (response.status === 'connected') {
userId = response.authResponse.userID;
accessToken = response.authResponse.accessToken;
var userinfo = getUserInfo(userId);
} else if (response.status === 'unknown') {
FB.login(function(response) {
statusChangeCallback(response)
}, {scope: 'public_profile,email'});
}
}
I'm getting the same issue, also using "cookie: true". But.. if I put the call to FB.login into the "status === 'unknown'" block, I get a blocked FB oauth popup - that is an empty window. I know I'm logged into Facebook (it's in the next tab over), I just don't understand why FB.loginStatus always returns "unknown".

how can I prevent native facebook login dialog in ios?

I am using facebooksdk.framework 3.1
when I login my app with my account, native login dialog pops up even though web based auth
completed. I need to turn off either native login dialog or web based auth but I don't know how.
I tried to find facebook.m file but there was no such file on facebooksdk.framework 3.1
how do I turn off safariauth or native auth?? It is very strange two login process occurs at the
same time.
First of all go to facebook.m page & try to find the following method:
- (void)authorize:(NSArray *)permissions
delegate:(id<FBSessionDelegate>)delegate
localAppId:(NSString *)localAppId
in this method there is a line:[self authorizeWithFBAppAuth:YES safariAuth:NO];
change authorizeWithFBAppAuth & safariAuth to yes/no according to your need.Hope it helps you.
Or you can try to implement latest Share kit sdk.it is best way.
If you use phonegap facebook plugin, you should call FB.getLoginStatus() carefully.
If FB.getLoginStatus() fires before FB.init() is done, the function would return a response as
'not connected' even if user is already connected.
my login problem was due to FB.getLoginStatus() on my redirected page.
even if user succed login and procceded to my redirected page, the page run FB.getLoginStatus()
and result was always 'not connected' because FB.init() not completely executed.
facebook provides async function to solve this problem but it didn't work when I tested on phonegap.
to check user login, I use FB.Event.subscribe and localstorage for now.
on the page that needs FB functions, I added this javascript code
FB.Event.subscribe('auth.login', function(response){
localStorage.setItem('fblogin', true);
console.log('login event');
}
FB.Event.subscribe('auth.logout', function(response){
localStorage.setItem('fblogin', false);
console.log('logout event');
}
document.addEventListener('deviceready', function(){
try{
FB.init({ appId : '1234567889' , nativeInterface : CDV.FB, useCachedDialogs : true});
}catch(e){
alert(e);
}
var fbval = localStorage.getItem('fblogin');
if(fbval){
// your code for connected status
}
});
basically, I set 'fblogin' localStorage value true whenever login event occurs,
and set the value 'false' whenever logout event occurs.
by comparing 'fblogin' value, I check users are logged or not.

User permission dialog doesn't pop-up for tab application

I have a strange behavior for an application that I have implemented and that captures the user's info when accessed.
The application, if accessed from outside Facebook URL, pops-up correctly a JavaScript permission dialog.
But when I inserted this application as a tab application into a Facebook page the permission request dialog doesn't pop-up anymore. Moreover, I have also placed in an FB.getLoginStatus() implementation the detection of the user's current login status in Facebook, with a JavaScript alert pop-up window if the user is not logged in. When the application is called from 'outside' the alert is triggered. When the application is on a Facebook page tab it doesn't.
Is this the correct behavior? If so, how can I enable the permission request in a Facebook tab application. I'm using both JS and PHP Facebook SDKs.
Edit 1 (following CBroe comment):
I'm using the following calls in the application's content.php markup (executed on page load):
<!-- Facebook JS SDK initialization -->
<div id="fb-root"></div>
<script>initFacebookJSSDK();</script>
<!-- End of Facebook JS initialization -->
<script>checkAccessPermission();</script>
<?php include_once 'sites/www.mysite.com/custom_code/custom_index.php';?> // I'm doing
custom code under Drupal
The JavaScript functions are implemented in the custom.js file, as following:
function initFacebookJSSDK() {
window.fbAsyncInit = function() {
FB.init({
appId : 'xxxxxxxxxxxxxxxxxx', // Application's ID
channelUrl : 'www.appsite.com/channel.html', // Channel File
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true, // parse XFBML
oauth : true // enable OAuth
});
.........
});
.........
}
function getPerms() {
FB.login(function(response) {
if (!response.authResponse) {
//user refused to grant permissions, redirect to the 'index' page
window.location = "/index";
}
}, {scope:"email"}); // I request the permission to get the email address
}
function checkAccessPermission() {
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
//user has granted permissions to the application
var uid = response.authResponse.userID; // not used
var accessToken = response.authResponse.accessToken; // not used
}
else if (response.status === 'not_authorized')
// user is logged into Facebook but didn't grand permissions to the app
getPerms();
else {
//user has not granted permissions, redirect to the 'index' page
alert('Please connect with your Facebook account');
window.location = "/index";
}
});
}
The PHP script - file 'custom_index.php' contains the following snippets:
$config = array();
$config["appId"] = FB_APP_ID;
$config["secret"] = FB_SECRET_ID;
$config["cookie"] = true;
$facebook = new Facebook($config);
// get user UID
$fb_user_id = $facebook->getUser();
// user's first visit, force the permission request window
if ($fb_user_id == 0) {
$location = $facebook->getLoginUrl(array('scope' => 'email'));
..........
}
// user already gave permission, get the profile and process
if ($fb_user_id != 0) {
$access_token = $facebook->getAccessToken();
$user_profile = $facebook->api('/me', array('access_token'=>$access_token));
..........
}
Again, it works very well when the user visits the site outside Facebook, but the permission request pop-up window doesn't show-up when it runs as Facebook tab application (frame inside Facebook). To note that, concerning my previous posting, now the JavaScript statement:
alert('Please connect with your Facebook account');
is executed in both cases, including when the application is run as tab app inside Facebook (I had just to clear the browser's cache).
Here is the solution.
All the code above is correct and stays in place.
I just added a jQuery function on the link that pulls-up the 'content.php' page, as following (the class '.open-content-page' is on the parent page of 'content.php'):
$(document).ready(function () {
$(".open-content-page").click(function() {
checkAccessPermission();
});
});
})(jQuery);
You’re calling your JS function without any user interaction – have you made sure it’s not just your browser’s popup blocker that keeps the dialog from coming up? (Maybe it distinguishes between popups called from a „simple” page vs popups from pages embedded in iframes on other domains.)
Since you can’t rely on your site’s users having their popup blockers set very liberal, it’s generally a better idea to call facebook dialogs on user interaction, f.e. when the user clicks a link/button. Popups called on user interaction are less likely to get blocked than popups that want to open all by themselves.

Permissions on fan page

How do I get permission on an application I have on a fan page tab and stay on the current tab?
I am collecting permissions on the application fine, but when I put the application onto a tab, it goes haywire seemingly getting caught in a never-ending loop and never going anywhere.
You could do this with the JavaScript SDK:
//Facebook connection with the JavaScript SDK
FB.init({
appId: 'YOURAPPID',
cookie: true,
xfbml: true,
status: true });
FB.getLoginStatus(function (response) {
//If you have permissions already
if (response.session) {
//Do application stuff...
}
else {
//Redirect browser to the permission dialogue
top.location="https://www.facebook.com/connect/uiserver.php?app_id=YOURAPPID&method=permissions.request&display=page&next=REDIRECTPAGEURI&response_type=token&fbconnect=1&perms=email,read_stream,publish_stream,offline_access";
}
});
You put in your application ID in the fb.init function, and then adjust the redirect for the permissions dialogue so it includes your application ID, the URI you want to re-direct to after the user accepts the permission dialogue, and finally the permissions you want to get (in this case I included email, read stream, publish stream and offline access token).

Facebook Connect disable auto login

I integrated the graph api facebook connect but if we are login to facebook, we will automatically login to the site with facebook connect as well. Is there any way we let the user clicks on fb "Login" only then the user is connected to the site with their fb account?
Now the user is automatically login to the site without the option to choose whether they would want to use their facebook account. If they want to logout from the site, they need to logout from facebook completely only then they can logout from the site with facebook connect as well.
Anyone can help me or give some tips how to go about?
Thank you!
I had this same problem on a recent website, and found a way to overcome it. My solution allowed a user to already be logged into facebook on their computer, yet not have it auto login on my website, then they can login with Facebook Login button and finally when they logout it won't log them out of Facebook on their computer, just on my website (much like Digg does with facebook).
To do it I was using https://github.com/facebook/php-sdk/ to check within PHP if there was an active facebook session with the user and the website (which would cause the auto login). If there was, I would not echo the auto login code:
FB.init({
appId : '<?php echo $facebook->getAppId(); ?>',
session : <?php echo json_encode($session); ?>, // don't refetch the session when PHP already has it
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
FB.Event.subscribe('auth.login', function() {
window.location = "process-login.php";
});
but instead just render my own facebook login button that would link to "process-login.php".
process-login.php would set the custom $_SESSION variable that told my website someone was logged (whether via my own system, or via facebook), and then reload the referring page (using $_SERVER['HTTP_REFERER']) which would now display the user as logged in via Facebook since my own $_SESSION variable was now set. To log them out (without logging them out of Facebook entirely, just my website), I would just load a logout script that removed the $_SESSION variable.
The example.php (in the php-sdk on github) was very helpful at finding my solution, though I had to customise it significantly to make it work with my existing system. It at least helped me see how to access the facebook session variable in PHP (stored in $me in the example).
Hope this helps you if its still a problem, or that it helps someone else in this situation.
EDIT:
Turns out I still had some issues with auto login on the rare occasion. To fix it I removed the event.subscribe('auth.login') and make a facebook button that called the following function to check login status before subscribing to the auth.login even. Here is the function:
function check_login_session(){
FB.getLoginStatus(function(r){
if(r.session){
window.location = '/process-login.php';
}
else{
FB.Event.subscribe('auth.login', function(response) {
window.location = '/process-login.php';
});
FB.login();
}
});
}`
I had the same problem, I guess that you are using the scripts provided by facebook. In that case you have a function associated with the window.fbAsyncInit event. This happens everytime that the page is loaded.
At the end of this method you have the code:
FB.getLoginStatus(function(response) {
statusChangeCallback(response);
});
The function statusChangeCallback verifies your user's facebook status (connected, authorized, or unknown). Here, if the user is "connected" you log him into your site. Well that's the problem, you are always trying to log the user in with facebook.
This must only happen on click, so you should erase those lines
hello dear I think you have made your question so confused. Your question is not stating what actually do you want. As for as I have understood I think you want to connect the user to you site through facebook connect and you want when user clicks on facebook logout, it automatically logouts from your site.
if my understanding about your question is right then simply let the user to login through facebook and do logins in your system in FB.Event.Subscribe event.
Use the following code for login button
<fb:login-button perms='email' autologoutlink='true'>
When user will allow your his facebook account to connect with your site
<div id="fb-root">
<script>
window.fbAsyncInit = function() {
FB.init({appId: "Your APP ID",
status: true,
cookie: true,
xfbml: true});
FB.getLoginStatus(function(response) {
if (response.session) {
// Send here parameters that logins to your system through your website login system
} else {
}
});
FB.Event.subscribe("auth.login", function(response) {
window.location.reload();
});
FB.Event.subscribe("auth.logout", function(response) {
window.location.reload();
//Send the Parameters that logouts user from your website through your website logout system;
});
};
(function() {
var e = document.createElement("script");
e.type = "text/javascript";
e.src = document.location.protocol +
"//connect.facebook.net/en_US/all.js";
e.async = true;
document.getElementById("fb-root").appendChild(e);
}());
and put the above whole code right after your <body> tag
If You have:
FB.Event.subscribe('auth.login', function() {
fbLogin(this);
});
Try to comment it /* fb.Event..... */