Detecting if a facebook user allowed or disallowed login - facebook

I am using FB's Javascript SDK using the login-button:
<fb:login-button onlogin="onFBLogin();">
How can I detect within onFBLogin() if the user did log in successfully ? Currently it is called everytime, no matter what the user chooses.
Thanks,
Meir

I think the first parameter passed into onFBLogin() is going to be either a response or a session object. So check to see what the value of response or response.session is.
Also, have you played around with FBJS's login event handling?
If using FB.login:
FB.login(function(response) {
if (response.session) {
// user successfully logged in
} else {
// user cancelled login
}
});
But since you're using an fb:login button, you can try to subscribe to the login event:
FB.Event.subscribe('auth.login', function(response) {
// do something with response.session
});
I haven't tried this myself via fb:login button, but hopefully this will get you on the right track.

Related

FB.login distinguish successful login from cancel if the user connected the app before

We have an FB.login call like this:
FB.login(function (response) {
if (response.status === 'connected') {
responseFunction(response.authResponse.userID);
} else {
responseFunction(null);
}
}, { scope: requiredPermissions.concat(optionalPermissions).join(','), return_scopes: true });
It properly detects a canceled login if the user didn't connect to the app yet. However, if the user is already connected when they cancel the login, response looks like this:
authResponse: {
accessToken: "token",
data_access_expiration_time: 1560437437,
expiresIn: 86963,
reauthorize_required_in: 7776000,
signedRequest: "bababa",
userID: "userid"
},
status: "connected"
Almost exactly like a successful login response. Luckily, there is also a grantedScopes field in the response if the login has been finished properly (because of a return_scopes option). However, using it to distinguish between the 2 seems unreliable and hacky.
Is there a better way?
Thank you in advance!
Update:
Why not use FB.getLoginStatus instead?
For the context: in my case, FB.login is used to be granted access to the user's pages. It is not used to log them into the app, per se.
I'll be happy if someone points at a mistake in my reasoning. Here it is:
Calling FB.login right after FB.getLoginStatus is unreliable due to the modal block in browsers. FB.login needs to be called synchronously within a click handler.
FB.getLoginStatus result may and will expire if called before showing the button calling FB.login. A user may and will spend a lot of time on this particular page before clicking the button.
That's why the button click handler immediately calls FB.login. It helps avoid both of the mentioned issues.
I ended up using the presence of grantedScopes in response as an indicator of a complete login.

How to bind Facebook onlogin event to customized button?

I know how to use custom button as Facebook login.
Now I'd like to bind onlogin event to customized button, but I don't know how to do.
Original code
<fb:login-button scope="public_profile,email" onlogin="afterLogin();">
</fb:login-button>
<script>
/* Assume that Facebook SDK loaded asyncronously and initilized */
function afterLogin() {
// Do stuff
}
</script>
My code
<button id="cusomized-button" onclick="fbLogin();" onlogin="afterLogin();">
Customized button
</button>
<script>
/* Assume that Facebook SDK loaded asynchronously and initialized */
// Show facebook login modal
function fbLogin() {
FB.login(function() {}, {
scope: 'email,public_profile'
});
};
function afterLogin() {
// Do stuff
}
</script>
Assuming you use version 2.4 of the Graph API, you are able to subscribe to an event called auth.login which is fired whenever the login status changes.
So, if you want to react to when the user logs in, you can do this and your function named afterLogin would be called once the user logs in to your app:
FB.Event.subscribe('auth.login', afterLogin);
Do note that Facebook recommends everyone to listen to auth.statusChange instead, otherwise your application will not know if the user has logged out or deauthorized the application, which would invalidate the token.
Here's an example using auth.statusChange, the response argument passed to the function contains a response object which is detailed here:
FB.Event.subscribe('auth.statusChange', function(response) {
if(response.status === 'connected') {
// `connected` means that the user is logged in and that your app is authorized to do requests on the behalf of the user
afterLogin();
} else if(response.status === 'not_authorized') {
// The user is logged in on Facebook, but has not authorized your app
} else {
// The user is not logged in on Facebook
}
});
As an alternative, the first argument to FB.login is a function which is called after the user returns from Facebook, so you could do something like this:
FB.login(function(response) {
if (response.authResponse) {
afterLogin();
} else {
// The user cancelled the login or did not authorize your app
}
}, {
scope: 'email,public_profile'
});
Here's an alternative using onlogin() in the way you originally wanted.
There's a subtle reason why you may need this:
You are using Facebook login just as a way to login to your own website
User is already connected (has previously connected to your FB)
User is NOT logged into your website.
You don't want to magically log someone in just because they're 'connected' It's not a good user experience.
So you show them the 'Login' button and once clicked you log the user in locally (provided you've established a linkage before).
In that case you do the following in the button code.
onlogin="window.fbOnLogin()"
Then depending upon your environment, somewhere in your code you would need to create a function on window. I'm using an Angular service and doing the following. This is typescript, so omit the <any> part if you're using pure JS.
constructor()
{
// Pure JS
// window.fbOnLogin = this.onLogin;
// Typescript (use lambda to keep 'this')
(<any>window).fbOnLogin = () => this.onLogin();
}
onLogin() {
call_my_server_to_login(token);
alert('Thanks for logging in with Facebook');
}
Now you can display the button to the user (and you secretly already know they're a user because the auto.authResponseChange event (or FB.getLoginStatus()) has told you they are "connected".
Note: None of the events, including auth.login will actually get triggered if you just click the button.
Once they click it FB returns immediately (becuase you're already logged in and connected) and calls your function. You then login the user your own website (you have to do a server side lookup to make sure they already logged in before). If you don't know who the user is then you have to do one of those 'associate your username' pages.

How would I set a PHP session via JavaScript (Facebook SDK)

I'm creating a Login Function using Facebook's SDK. I'm re-using code from a previous project that had a Login button which redirected to a Login Box on the Facebook Domain (i.e. the Login box was not a popup, but redirected the user).
In the previous project when the user would come back to the site after accepting the app, there was a PHP script which created a $_Session:
$user = $facebook->getUser();
if (isset($user)){
$_SESSION['LoggedIn'] = $user;
}
I could then use the 'LoggedIn' session to check if the user was logged in or not, and modify the page based on that (e.g. replace content on the page).
Here's my question - I am now using the JS code that Facebook provides for a popup Login box. I'm guessing after the user Accepted the app from the Login Popup I need to start the session from within JavaScript? The problem is I can't figure out how....
$(".facebookButton").click(function(){
FB.login(function(response) {
if (response.authResponse) {
//User accepted the app -I need to start the SESSION here?
} else {
//User hasn't accepted the app.
}
});
});
Basically what I'm trying to achieve is for the site to know whether the user is logged in or not, even after they've refreshed the page. Thanks for the help!
When the user logs in using the JavaScript SDK, a cookie is immediately dropped on your site with their auth details. The dropped cookie can also be ready by the PHP SDK so all you need to really do is refresh the page for the PHP SDK to detect the user:
$(".facebookButton").click(function(){
FB.login(function(response) {
if (response.authResponse) {
// reload page
location.reload();
} else {
// User hasn't accepted the app.
}
});
});

PhoneGap; FB Connect Plugin (Android OS): Re-Authorizing FB App every post

I created an Android App with PhoneGap:Build and the FB Connect Plugin. The app works fine and the FB Plugin, too. Just one tiny thing isn't working yet. I won't to post something after submiting a button which works, too. At the first time the user has to login and grant permissions to the FB App and them the post is published. That's the way it should be. And the next time the user submits the post should be published without the whole permission thing but this isn't working!? FB shows a message like "You already granted permission ... to the app." and the user has to push the Ok-button before the post is published???
Because I still haven't found an answer for my question, maybe I just do something wrong in my FB Javascript call? Here is the current code:
FB.login(function(response) {
if (response.authResponse) {
var data = {
...
}
FB.api('/me/feed', 'post', data, function(response) {
// Callback
if (!response || response.error) {
// ERROR
}
});
} else {
// ERROR
}
}, {scope: 'publish_stream'});
Well, to better understanding here a picture of the screen that apears every post:
http://i.stack.imgur.com/bZrde.png
Thx,
Daniel
I think the solution to this problem is to not include the login request every time you want to post something. You can check login status, and/or permissions, without performing a login. Then, if the user is not logged in, do the login first, and come back to the new post action.

Facebook application: FB events work only for first time

I'm using the following code to subscribe to fb login and logout events.
FB.Event.subscribe('auth.logout', function(response) {
RefreshPageOnFBStatusChange(response);
});
FB.Event.subscribe('auth.login', function(response) {
RefreshPageOnFBStatusChange(response);
});
function RefreshPageOnFBStatusChange(response)
{
alert(response.status);
}
I want to redirect users to different pages when they are logged in or logged out. The function I'm using here gets called only during the actual page load, and never after that. I have a fb-like, fb-share and live stream plugin on a page. When I login and logout of live stream, nothing happens. Help!
Please modify your question and provide all FB-related code.
This may answer you question:
Facebook FB.Event.subscribe event does not fire:(
For User Status you can use if(FB._userStatus == "connected"){} to check user is login or not And for Logout & login you can use following simple code
FB.logout(function(response) { window.location = redriect_uri;
});
It seems like these events don't fire when you use the live chat plugin because it has its own way of handling the login and logout. What I had to do to solve this problem was to set a timeout of 5 seconds and call a javascript function that did a FB.GetLoginStatus, and based on what it was I would refresh the page. Not the best way of doing it, but I was left with no choice.