Refreshing FB Access Token with Javascript SDK - javascript

For context I am trying to build a small microsite to pull social media insights from Facebook. I am looking to build a Django backend and React front end.
I would like to implement FB login with the Javascript SDK since according to the docs this refreshes the access token each time a FB call is made using the SDK.
I have a very simple login script taken from FB official docs which literally just logs in the user and then outputs the list of accounts the user has access to.
The issue is that, despite refreshing the page (and therefore performing an API request) the data expiration date doesn’t extend (it still displays the date of first login).
Is anyone familiar with the Javascript SDK and whether this is normal behaviour?
function statusChangeCallback(response) { // Called with the results from FB.getLoginStatus().
console.log(response);
if (response.status === 'connected') { // Logged into your webpage and Facebook.
testAPI();
FB.getAuthResponse(function(response){
console.log(response.authResponse.accessToken);
});
} else { // Not logged into your webpage or we are unable to tell.
document.getElementById('status').innerHTML = 'Please log ' +
'into this webpage.';
}
}
function checkLoginState() { // Called when a person is finished with the Login Button.
FB.getLoginStatus(function(response) { // See the onlogin handler
statusChangeCallback(response);
});
}
window.fbAsyncInit = function() {
FB.init({
appId : 'APP_ID_GOES_HERE',
cookie : true, // Enable cookies to allow the server to access the session.
xfbml : true, // Parse social plugins on this webpage.
version : 'v13.0' // Use this Graph API version for this call.
});
FB.getLoginStatus(function(response) { // Called after the JS SDK has been initialized.
statusChangeCallback(response); // Returns the login status.
});
};
function testAPI() { // Testing Graph API after login. See statusChangeCallback() for when this call is made.
console.log('Welcome! Fetching your information.... ');
FB.api('/me/accounts',
function(response) {
console.log(response)
});
}
function logout_js_user(){
FB.logout(function(response) {
// Person is now logged out
});
};

FB.getLoginStatus does refresh the Token, but not on every Page call. It only refreshes the Token when it is not valid anymore. That is why the expiration data does not change.
You can can a more accurate status with the second parameter of the function set to true, but be aware that this might affect performance:
FB.getLoginStatus(function(response) {
// this will be called when the roundtrip to Facebook has completed
}, true);
If you call FB.getLoginStatus on every page load, be careful not to
set this parameter for each as it will significantly increase the
number of requests to Facebook's servers, and thus decrease the
performance of your application.
Side note: ou can use FB.login to make the login less complicated (in my opinion) - here's an old but still valid article about that: https://www.devils-heaven.com/facebook-javascript-sdk-login/

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?

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

fb.login run dialog in the background?

in order to check if the user has provided all the permissions i need for my app, I do it so:
/*Solo hacemos la peticion si el checkbox estaba desmarcado. Nota: esta funcion asume que solo hay un checkbox en el dom*/
if($('input:checkbox').prop('checked')){
FB.login(function(response){
console.log(response.status);
if (response.status == 'connected') {
hi /* Entonces listo */
}else{
/* Entonces cancelamos el checkbox */
$('input:checkbox').removeAttr('checked');
}
}, { scope: 'publish_stream' });
}
This way:
if user did it allready: a popup is opened for less than a second
if user didnt yet: the permission dialog is shown
Question is: how can i prevent the dialog to be opened (maybe running it in the background) in the first case?
You cannot stop a popup when you use FB.login.
Either use a server side authentication or use FB.getLoginStatus to prevent popup in first case.
FB.getLoginStatus allows you to determine if a user is logged in to
Facebook and has authenticated your app
Refer Facebook docs
A snippet from the above reference link,
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
// the user is logged in and has authenticated your
// app, and response.authResponse supplies
// the user's ID, a valid access token, a signed
// request, and the time the access token
// and signed request each expire
var uid = response.authResponse.userID;
var accessToken = response.authResponse.accessToken;
} else if (response.status === 'not_authorized') {
// the user is logged in to Facebook,
// but has not authenticated your app
} else {
// the user isn't logged in to Facebook.
}
});
This is what you need.
Edit: (after OP's comment)
May be facebook is caching old result.
From the same link I mentioned above,
Roundtrips to Facebook's servers
To improve the performace 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 JD 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);
If you call FB.getLoginStatus on every page load, be careful not to
set this parameter for each as it will significantly increase the
number of requests to Facebook's servers, and thus decrease the
performace of your application.
The facebook sdk login() function opens a pop up by default, as you can read in the Documentation.
so that's not the way you wanna go.
There are 2 simillar question that you might find it's info useful.
Try This and This.

Logged out of Facebook but it still reconginizes $user

All,
I'm using Facebook Connect (JS SDK) to authenticate a user to my site. I'm checking to see if a logged in session variable is set on my site before even hitting code to check to see if a user is logged into facebook. This all works great however, when the user logs out of facebook and logs out of my site and I try and go back to my login back it still thinks that the user is logged into facebook even though I know they aren't. How can I prevent this from happening? I tried to set autologoutlink=true on my login button but it doesn't seem to be working.
Any ideas?
Thanks!
The solution provided by #Madan worked for me. Since my application is ajax based, therefore I can't reload the browser. I run a setInterval() call back function every minute to check if user is still logged in to facebook.
setInterval(function (){
FB.getLoginStatus(function(response){
if(response.status ==='unknown' && FB_LOGIN==1){
alert('Your Facebook session has been expired');
member_logout();
}
}, true);
},60000);
it worked like a charm.
Always give second parameter in FB.getLoginStatus( callback, true) as true...this is because facebook response is cached in SDK. So use alway true param for current user session check.
I've always had excellent results when calling FB.getLoginStatus() and redirecting the user to the appropriate content based upon those results. Three conditions (although for an app, the second two are quite the same in my opinion)
https://developers.facebook.com/docs/reference/javascript/FB.getLoginStatus/
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
// the user is logged in and connected to your
// app, and response.authResponse supplies
// the user's ID, a valid access token, a signed
// request, and the time the access token
// and signed request each expire
var uid = response.authResponse.userID;
var accessToken = response.authResponse.accessToken;
} else if (response.status === 'not_authorized') {
// the user is logged in to Facebook,
//but not connected to the app
} else {
// the user isn't even logged in to Facebook.
}
});
$facebook->destroySession();
or u can go to this link
Facebook getUser() function returning user ID after logout

Categories

Resources