Facebook callback right after opening the Oauth popup - javascript

I'm using the login flow suggested by the fb documentation;
Html
Click me to login!
JavaScript
//USER WANTS TO LOGIN
$("a").click(function() {
FB.login( checkLoginState(), { scope: 'email,user_birthday,user_likes' });
})
//CALLBACK LISTENER OF WHAT THE USER CHOOSE
function checkLoginState(mode) {
FB.getLoginStatus(function(response) {
statusChangeCallback(response);
});
}
//WHAT TO DO DEPENDING ON WHAT THE USER CHOOSE
function statusChangeCallback(response) {
if (response.status === 'connected') {
//LIFE IS GOOD
alert("Thank you, know my php script will handle the rest");
} else if(response.status == 'not_authorized') {
//THE USER DOES NOT AUTHORIZE
alert("Im sorry, you have to authorize the app in order to proceed");
}
}
The problem is, when I call FB.login, the popup opens as it should asking the user to login or authorize my app, BUT, as soon as the popup opens the statusChangeCallback is called giving me an status. I don't get why the SDK is giving me a callback as soon as it opens, the user needs to "say something" (login, or authorize or not the app) in order to trigger a response. You see, with this flow, as soon as the user clicks the login button the alert Im sorry, you have to authorize the app in order to proceed will popup. Also, worst, is the fact that when the user introduce its credentials in the popup and authorize the app, there is no callback...
What am i missing?

checkLoginState needs to be passed int FB.login() as a function. You are calling it.
your click event binder should look like this:
$("a").click(function() {
FB.login( checkLoginState, { scope: 'email,user_birthday,user_likes' });
})

Please make the below change and try.
//USER WANTS TO LOGIN
$("a").click(function() {
FB.login( checkLoginState, { scope: 'email,user_birthday,user_likes' });
})
//CALLBACK LISTENER OF WHAT THE USER CHOOSE
var checkLoginState=function() {
FB.getLoginStatus(function(response) {
statusChangeCallback(response);
});
}
//WHAT TO DO DEPENDING ON WHAT THE USER CHOOSE
function statusChangeCallback(response) {
if (response.status === 'connected') {
//LIFE IS GOOD
alert("Thank you, know my php script will handle the rest");
} else if(response.status == 'not_authorized') {
//THE USER DOES NOT AUTHORIZE
alert("Im sorry, you have to authorize the app in order to proceed");
}
}

Related

auth.authResponseChange event callback fires when FB.getLoginStatus() is called?

I am trying to implement the FB JS SDK on my website, both for logging in and also for sharing/liking content.
Here is my code:
// called by FB SDK once loaded (all.js)
window.fbAsyncInit = function () {
FB.init({
appId : '913550365396947',
cookie : true, // enable cookies to allow the server to access the session
xfbml : true, // parse social plugins on this page
version: 'v2.5',
status: false // don't check login status
});
FB.getLoginStatus(function (response) {
console.log('FB.getLoginStatus callback response', response);
});
// auth.authResponseChange event is fired for any authentication related change, such as login, logout or session refresh
FB.Event.subscribe('auth.authResponseChange', function (response) {
console.log('auth.authResponseChange callback response: ', response);
// Here we specify what we do with the response anytime this event occurs.
if (response.status === 'connected') {
if (!shopWise.loggedIn) { // if the user isn't logged in to PW, but they are logged in to facebook
console.warn('Logged in with facebook, but not logged in to shopwise. Reloading the page..');
location.reload();
}
} else if (response.status === 'not_authorized') {
} else {
}
});
};
The problem I'm having is that the auth.authResponseChange callback is being executed on every page load, while (if my understanding is correct) it should only be executed when the user's login state actually changes (such as logging in, or logging out).
Because the event is called on every page load, my page refresh code is executed on every page load, which means the page is in an endless refresh loop.
What's strange is that if I remove the FB.getLoginStatus() call, the auth.authResponseChange callback is not fired.
What am I doing wrong here? Why is calling FB.getLoginStatus() causing the auth.authResponseChange callback to be fired?

Facebook javascript SDK login https: works only if you login twice

EDIT: please check the workaround at the end of this question.
There are a lot of similar threads but I cannot find the same problem.
Basically, we moved our login page to HTTPS.
When the page was HTTP, everything was working great, without problems.
The flow was:
The user opens the login page
The user clicks on the Facebook login button
The user performs the FB authentication
The user is redirected to PAGE2
Now the flow is:
The user opens the login page
The user clicks on the Facebook login button
The user performs the FB authentication
The user is redirected on the login page again!
The user clicks on the Facebook login button
The user is redirected to PAGE2
So, the user has to perform the operation twice.
The code:
window.fbAsyncInit = function () {
FB.init({appId: HERE_MY_APP_ID,
status: true,
cookie: true,
xfbml: true,
oauth: true});
FB.getLoginStatus(function (response) {
console.log(JSON.stringify(response));
if (response.status == 'connected') {
// Something here
}
});
};
(function (d) {
var js, id = 'facebook-jssdk';
if (d.getElementById(id)) {
return;
}
js = d.createElement('script');
js.id = id;
js.async = true;
js.src = "//connect.facebook.net/it_IT/all.js";
d.getElementsByTagName('head')[0].appendChild(js);
}(document));
And this is the function called when the user clicks on the Facebook button:
function fblogin() {
FB.login(function (response) {
if (response.status == 'connected') {
login();
} else {
// user is not logged in
window.location.reload();
}
}, {scope: 'email,publish_stream'});
return false;
}
Please note that debugging this code, the response printed in the getLoginStatus function says that response.status is unknown the first time, but when the page reloads, the response object is filled correctly, with response.status that is connected!.
How can I debug this issue? Any hints?
** WORKAROUND **
I've moved the getLoginStatus code from fbAsyncInit to the FB.login callback and now it works. But it's just a workaround, probably.

how to detect log out from fb using JS SDK without refreshing the page

Hi friends,
I'm developing a website in which Facebook Javascript API is used to send message to our friends.
When the user is logged out of fb,then it shows an error when popping up js API dialog box which is
"Refused to display 'https://www.facebook.com/login.php?api_key=0&skip_api_login=1&display=dialo…cale%3Den_US%26name%3DAnything%26to%3D1791715188%26from_login%3D1&rcount=1' in a frame because it set 'X-Frame-Options' to 'DENY'."
Currenty,I'm using FB.getLoginStatus to detect whether the user is logged out or not. But this will work for only first time,I can't dynamically check it(That means when I logged out of fb account and coming back to the same window and trying to send next message without refresh,it shows the above error.).
Here How Can I dynamically detect that the user is currently logged out. Is there any way to checking FB.getLoginStatus dynamically without page refresh.
I'm showing my code below.
$(document).ready(function(){
window.fbAsyncInit = function() {
FB.init({appId: '**************', xfbml: true, cookie: true,status:true,oauth:true});
/*FB.Event.subscribe('auth.login', function() {
//window.location.reload();
});*/
FB.Event.subscribe('auth.logout', function(response) {
alert('logged out!');
});
};
function facebook_send_message(to,name) { //function called when a button is clicked
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
console.log('how to check');
var uid = response.authResponse.userID;
var accessToken = response.authResponse.accessToken;
send_message(to,name);
}
else if (response.status === 'not_authorized') {
console.log('not_authorized');
// the user is logged in to Facebook,
// but has not authenticated your app
}
else
{
console.log('hi');
FB.login(function(response) {
if (response.authResponse)
{
send_message(to,name);
//getUserInfo(); // Get User Information.
} else
{
console.log('Authorization failed.');
}
},{scope: 'email'});
}
});
}
send_message(to,name); will send message if user is logged in,
Currently for the first time,it works clearly,but from the second time without page refresh and if we logged out from fb, then FB.getLoginStatus still shows response.status as 'connected' and hence error occured.
Waiting for your kind replies.
Thanks in Advance
According to Facebook,
https://developers.facebook.com/docs/reference/javascript/FB.getLoginStatus/
To improve the performance of your application, not every call to check the status of the user will result in request to Facebook's servers. Where possible, the response is cached. The first time in the current browser session that FB.getLoginStatus is called, or the JS SDK is init'd with status: true, the response object will be cached by the SDK. 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);

FB.login is always asking my password (even if I'm already logged in)

I'm playing with Facebook Javascript SDK in order to implement a Facebook Connect action. It's already working but the problem is that every time that I try to login again on my application the user has to reenter its facebook password.
I'm sure that there is an option to do this step without entering the password if you are already logged in in facebook (I have seen this in lots of web pages). But how? The documentation http://developers.facebook.com/docs/reference/javascript/FB.login/ and even the source code does not explain how to do this:
"#param opts {Object} (optional) Options to modify login behavior."
My implementation right now is like this:
function login(){
FB.login(function(response) {
if (response.authResponse) {
$(".fb_login").hide();
$(".fb_logout").show();
FB.api('/me', function(response) {
register_user(response.id, response.name);
});
} else {
alert('User cancelled login or did not fully authorize.');
}
});
}
And I call to FB.init like this:
FB.init({
appId : 'xxxxxxxxx', // App ID
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
Maybe it has to be a change in the FB.init or some kind of option while calling to FB.login. Any ideas?
Thanks in advance,
Raimon Bosch.
There is a method FB.getLoginStatus which you can use to check if user is already loggedin:
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
var accessToken = response.authResponse.accessToken;
//you are loggedin
} else if (response.status === 'not_authorized') {
//loggedin but not authorized your app
} else {
// the user isn't logged in to Facebook.
}
});
Did you mean something like that
Check the
Force Web OAuth Reauthentication in your PP setting facebbok developer>Your App> facebook login > setting > set Force Web OAuth Reauthentication to NO

Authorize Timeline app to user's profile and then do OpenGraph action

I'm pretty new to Facebook development, so been trying to read up on older questions but still a bit lost =\
Here's one that I'm struggling with:
Currently I have an app with several defined Open Graph actions i.e. "ask a question". Is there a way to provide a dialog box for users that do not have the app yet, so that after they authorize the app, it'll go ahead and do the OG action? Ideally, it'd happen smoothly and without multiple dialog boxes.
OG action:
FB.api(
"/me/beta_sandbox:ask?question=http://example/question/1",
'post',
function(response) {
if (!response || response.error) {
alert('Sorry, your question was not shared: '+response.error);
} else {
alert('Your question was successfully shared!');
}
});
Solution: redirect uri?
Any help would be greatly appreciated =)
You should authorize users prior to publishing an action.
You can nest the publishing of an action within FB.getLoginStatus method to publish action for logged in users and bring login dialog for user who not connected with app or logged out of Facebook:
var publishAction = function(){
FB.api('/me/beta_sandbox:ask?question=http://example/question/1', 'post',
function(response) {
if (!response || response.error) {
console.log('question was not shared', response);
} else {
console.log('question was successfully shared!');
}
}
);
}
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
// User is authenticated, Publish Action
publishAction();
} else {
// Bring Login Dialog to authenticate the user
}
}
You also may leverage FB.login method to publish action after user is logged in (for users who already logged in dialog will not be opened and closed immediately and callback will be called):
FB.login(function(response) {
if (response.authResponse) {
// User is authenticated, Publish Action
publishAction();
} else {
// User declined authentication
}
});

Categories

Resources