fb.login run dialog in the background? - javascript

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.

Related

Refreshing FB Access Token with Javascript SDK

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/

Firebase for web: telling whether user is logged in or not

I have a web app built on Firebase's web library. I want to restrict some pages to only users who are logged in.
This code triggers when firebase detects the user is logged in, which is good.
firebase.auth().onAuthStateChanged(function (user) {
console.log('User is logged in');
});
But I can't get anything to reliably check whether the user is not logged in without leaving the page before the above code has a chance to check...
var check_firebaseReady == false;
function local_initApp() {
if (check_firebaseReady == false) {
if (typeof firebase !== 'undefined') {
check_firebaseReady = true;
console.log(firebase.auth().currentUser); //not reliable becuase it may return an empty user before it has a chance to get an existing user
}
setTimeout(function () {
local_initApp();
}, 300);
}
}
local_initApp();
I think for single page apps, you have to use the onAuthStateChanged listener and enforce access via security rules on specific data. If you want to block access to a complete page, you are better off using a cookie system. Firebase Auth provides that option: https://firebase.google.com/docs/auth/admin/manage-cookies
With cookies, you would check and verify the cookie server side, otherwise, not serve the page and show some error or redirect to login page instead.

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);

How to synchronously check if app is still authorized with javascript sdk?

I tried it with:
var auth_response = FB.getAuthResponse();
But that always gives back the authResponse with access token even if the app had been deauthorized. I expected a different result.
I have also tried subscribing into the authResponseChange.
FB.Event.subscribe('auth.authResponseChange', checkFbAuthorization);
function checkFbAuthorization(response) {
if (response.status === 'connected') {
fb_authorized = true;
} else if (response.status === 'not_authorized') {
fb_authorized = false;
}
But checkFbAuthorization did not get called when I deauthorized the app from the facebook account settings page.
I also tried with just using fb.login but it did not open a popup if the app was deauthorized.
A possible explanation is that i should wait longer, i tried it several times to wait longer but also without result.
have a look at this demopage:
http://www.facebook.com/pages/Helper-Component-Community/222933037808340?sk=app_412923142052609
there is an button for checking if you are connected! Remember that you have to re-visit the app after removing the auth from your application list because the auth is saved for each visit via JS!
Edit: this one button just tests if you are connected. You can chain the requests and events to get an auth-workflow for your app :)

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