why is facebook js sdk web login callback not being called or called too early? - facebook-javascript-sdk

the problems
fb:login-button: with it, I can't log in.
FB.login(): with calling it by clicking a button, I'm able to log in but the callback function called too early before I log in or sign up so passes an unknown state response.
In case of fb:login-button
with facebook logged out, facebook login pop up pops up and when I log in, nothing happens(FB.getLoginStatus returns unknown state).
with facebook logged in, the pop up just flashes away and nothing happens(FB.getLoginStatus returns unknown state).
after both operation, checkLoginState() logs {authResponse: null, status: 'unknown'} neither status: 'not-authorized' or status: 'login'. It means I don't succeed to login I guess. Is that why the buttons onlogin callback is not called? (Cause it's called on login event)
In case of FB.login()
with facebook unknown state, when I click the button, the callback function is called before I login. It results passing unknown state response.
with FB.login() in console, FB.getLoginStatus returns successful login response.
Here is my html code
<body>
<script>
window.fbAsyncInit = function () {
FB.init({
appId: '...',
cookie: true,
xfbml: true,
version: 'v13.0'
});
FB.AppEvents.logPageView();
checkLoginState();
};
function checkLoginState() {
FB.getLoginStatus(function (response) {
statusChangeCallback(response);
});
}
function statusChangeCallback(response) {
console.log(response);
}
(function (d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {
return;
}
js = d.createElement(s);
js.id = id;
js.src = "https://connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
function facebooklogin(){
FB.login(function(response){
statusChangeCallback(response);
});
}
function facebooklogout(){
FB.logout(function(response){
statusChangeCallback(response);
});
}
</script>
<fb:login-button scope="public_profile,email" onlogin="checkLoginState();">
</fb:login-button>
<button onclick="facebooklogin();">fb-login</button>
Any answer would be appreciated.

I found the answer.
The keypoint is FB.logout function leaves a cookie which prevents anymore login attemps. like fblo_51245583...=y.
With the cookie,
if you are logged in facebook and try to login your web then the pop-up will disappear very quickly.
if you are not logged in facebook and try to login your web while the pop-up prompts you to login, the callback function will be called with unknown state response(I guess the logout cookie automatically deny the login attempt at all). and whether you succeed to login in facebook or not it takes no effect on the web.
But I still don't know why the fb:login-button doesn't work.
And when The callback function is still executed earlier than my log-in process.
My goal is
When users log in first time using facebook, they are signed up automatically with their uid value from authResponse.
While they are accepting or loggin in facebook, the callback function should wait until they accept/reject or login/not like event-driven.
But as I understand FB.login functions callback parameter doesn't wait for the action but just wait for a response from the facebook server.
So I need other approaches.
use event subscription refer to https://developers.facebook.com/docs/reference/javascript/FB.Event.subscribe/v13.0

Related

Google OAuth2 SignIn method fires at page load

I have used the official button for Google SignIn:
SignIn Page:
<div class="g-signin2" data-onsuccess="AuthenticateGoogleUser"></div>
function AuthenticateGoogleUser(googleUser){
.....
capture the user info and redirect to Home page
.....
}
When configuring for the credentials, I have set the redirection URL to the signin page.
This is how the Signout happens for the app:
function SignOutGoogleUser() {
if (gapi != null && gapi != undefined &&
gapi.auth2 != null && gapi.auth2 != undefined) {
var auth2 = gapi.auth2.getAuthInstance();
auth2.signOut().then(function () {
auth2.disconnect();
....Redirect to Home page...
});
}
}
The methods work fine. If I signout, will be redirected to home page.
But, when I manually browse the SignIn page after signout, the AuthenticateGoogleUser method is triggered and I am auto signed into the app (with google account).
The AuthenticateGoogleUser method should be only triggered on the button click. Is that right.
But here it is being triggered on load of SignIn page. Is that expected. Can this be stopped.
I'm using MVC C# as backend.
Without seeing all of your code, I am working on the assumption that you have not placed the function in a document ready wrapper and made sure to only kick it off on a button click or other event from which you would like to have it fire. As it stands now, it will fire on that page load.
$(document).ready(function(){
$("btnLogin").click(function(){
AuthenticateGoogleUser(googleUser);
});
});

Facebook JS SDK FB.Login function

In my website, I have a button for "facebook connect", which when clicked on, triggers the following code:
<script type="text/javascript">
$(document).ready(function(){
console.log(<?=(isLoggedIn()+0)?>);
$("#fbconnect").click( function(){
FB.login(function(response) {
alert(JSON.stringify(response.authResponse));
if (response.authResponse) {
window.location = window.location;
alert('Welcome! Fetching your information.... ');
} else {
alert('User cancelled login or did not fully authorize.');
}
}, {scope: 'email,user_likes'});
} );
});
</script>
The button works well: it shows the facebook login dialog, and then alerts the appropriate message. However, when I refresh the page, the user is still logged out both server-side and client-side. Do I need to handle the access token and cookies myself or does the javascript SDK take care of that? If the latter, then why doesn't this code work?
Thank you.
UPDATE 1:
It works perfectly on localhost with Firefox, and on the server with all browsers. So the problem exists only for chrome and on localhost. Is there some chrome security setting that prevents cookies from being saved for localhost?

Sencha touch 2 facebook login

I was trying to integrate facebook login feature in my sencha touch 2 application and I found the instructions on debvelopers.facebook.com. I was able to integrate the feature using that but the login window opens as a popup. Is there a way to make that login window open in the same tab and not as a popup.
here is my code for index.html
<script src="//connect.facebook.net/en_US/all.js"></script>
<script>
window.fbAsyncInit = function() {
console.log("FB.init")
FB.init({
appId : '***************', // App ID
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
});
(function(d){
var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
ref.parentNode.insertBefore(js, ref);
}(document));
}
</script>
this is the part of the code I used in aap.js which I got from debvelopers.facebook.com
FB.Event.subscribe('auth.authResponseChange', function(response) {
// Here we specify what we do with the response anytime this event occurs.
if (response.status === 'connected') {
// The response object is returned with a status field that lets the app know the current
// login status of the person. In this case, we're handling the situation where they
// have logged in to the app.
} else if (response.status === 'not_authorized') {
// In this case, the person is logged into Facebook, but not into the app, so we call
// FB.login() to prompt them to do so.
// In real-life usage, you wouldn't want to immediately prompt someone to login
// like this, for two reasons:
// (1) JavaScript created popup windows are blocked by most browsers unless they
// result from direct interaction from people using the app (such as a mouse click)
// (2) it is a bad experience to be continually prompted to login upon page load.
} else {
// In this case, the person is not logged into Facebook, so we call the login()
// function to prompt them to do so. Note that at this stage there is no indication
// of whether they are logged into the app. If they aren't then they'll see the Login
// dialog right after they log in to Facebook.
// The same caveats as above apply to the FB.login() call here.
}
});

Why won't CasperJS accept a redirect request after clicking on a link?

I'm having more Casper troubles, this time I've told Casper to click on a href that will redirect it to a page that will redirect it to the twitter app auth page:
var casper = require('casper').create({
verbose: false,
logLevel: 'debug',
waitTimeout: 10000
});
phantom.cookiesEnabled = true;
casper.start('http://foo.bar', function afterstart() {
if (this.exists('#back-to-top')) {
this.echo('BOOYA! foo.bar is loaded', 'INFO');
} else {
this.echo('Page didnt load, something went all screwy.', 'ERROR');
}
});
casper.then(function signin() {
this.click('a[href="/sys/login"]' );
});
casper.then(function tellsignin() {
if (this.exists('#not-logged-in ')) {
this.echo("I clicked on twitter login button, so now the twitter login page is loaded.", 'INFO');
} else {
this.echo('Twitter login link didnt work, something went wacky');
};
});
When I run it, the console error output is this, plus some other stuff that isn't important:
Test file: testingtest.js
BOOYA! foo.bar is loaded
Twitter login link didnt work, something went wacky
I've tried looking up explanations, and found this group thread, but it unfortunately doesn't provide any answers for my problem.
Does anyone know any possible reasons why Casper isn't redirecting?
I've resolved the issue thanks to all of your help and support, lol! What happened is that the tellsignin function was being executed before the browser had time to be redirected to the twitter app auth page, so I just added a this.waitForText('Authorize foo-bar app to use your account?') to the signin function.

Authentication in jQuery Mobile and PhoneGap

I have a web application built with jQuery Mobile and PHP (CodeIgniter framework). Now I'm trying to make a PhoneGap version of it as well, to make it distributable as a standalone app. However, the PHP web app. version uses Ion Auth, a CodeIgniter plugin for authentication. So when you go to a page that requires authentication, the app redirects you to the authentication controller login method. And after authentication it redirects you back to the home page (the jQuery Mobile page in this case). This works fine in the web app., since the home page is opened by the home controller in the first place anyway.
But here's the crux: in the PhoneGap version, the "home" page needs to be the index.html file in PhoneGap. Apparently you can load another url on startup by adding a value in PhoneGap.plist, but that is not acceptable by apple for submitting to app store. And if I do a redirect in the authentication, I can't get back to the index.html file after authentication...
So how should one go about authentication in a PhoneGap/jQuery Mobile app?
UPDATE:
I have tried this according to one of the answers, but the app still tries to navigate to the account/login page (which doesn't exist), when I just want to login through the post and return a value from the method:
$('#login_form').bind('submit', function () {
event.preventDefault();
//send a post request to your web-service
$.post('http://localhost/app_xcode/account/login', $(this).serialize(), function (response) {
//parse the response string into an object
var response = response;
//check if the authorization was successful or not
if (response == true) {
$.mobile.changePage('#toc', "slide");
} else {
alert('login failed');
$.mobile.changePage('#toc', "slide");
}
});
});
Here's the controller method:
function login()
{
//validate form input
$this->form_validation->set_rules('identity', 'Identity', 'required');
$this->form_validation->set_rules('password', 'Password', 'required');
$base_url = $this->config->item('base_url');
$mobile = $this->detect_mobile();
if ($mobile === false && $base_url != 'http://localhost/app_xcode/') //Only restrict if not developing
redirect('account/notAMobile');
else if ($this->form_validation->run() == true) { //check to see if the user is logging in
//check for "remember me"
$remember = (bool)$this->input->post('remember');
if ($this->ion_auth->login($this->input->post('identity'), $this->input->post('password'), $remember)) { //if the login is successful
//redirect them back to the home page
$this->session->set_flashdata('message', $this->ion_auth->messages());
echo true;
/*redirect($this->config->item('base_url'), 'refresh');*/
}
else
{ //if the login was un-successful
//redirect them back to the login page
$this->session->set_flashdata('message', $this->ion_auth->errors());
/*redirect('account/login', 'refresh');*/ //use redirects instead of loading views for compatibility with MY_Controller libraries
}
}
else
{ //the user is not logging in so display the login page
//set the flash data error message if there is one
$this->data['message'] = (validation_errors()) ? validation_errors()
: $this->session->flashdata('message');
$this->data['identity'] = array('name' => 'identity',
'id' => 'identity',
'type' => 'text',
'value' => $this->form_validation->set_value('identity'),
);
$this->data['password'] = array('name' => 'password',
'id' => 'password',
'type' => 'password',
);
}
}
I think I have removed or commented out any redirects that were there. So I don't know why it tries to load the view still? Does it have something to do with jQuery Mobile trying to navigate there because I post to that url?
The reason your form is still submitting and it's trying to change pages is because you have a syntax error in your submit handler Javascript. On line two, event is not defined so trying to call event.preventDefault() errors. Although the handler fails, the browser still submits the form using it's default action and method.
Either change your function signature to function(event) { or simply return false from the function. Returning false is equivalent to preventing default.
$('#login_form').bind('submit', function () {
//send a post request to your web-service
$.post('http://localhost/app_xcode/account/login', $(this).serialize(), function (response) {
//check if the authorization was successful or not
if (response == true) {
$.mobile.changePage('#toc', "slide");
} else {
alert('login failed');
$.mobile.changePage('#toc', "slide");
}
}, 'JSON');
return false;
});
You can make requests to your web-service (Ion Auth) from your app. with jQuery. Your login would look something like this:
//add event handler to the `submit` event for your login form
$('#login_form').bind('submit', function () {
//send a post request to your web-service
$.post('http://my-domain.com/my-auth/auth.php', $(this).serialize(), function (response) {
//parse the response string into an object
response = $.parseJSON(response);
//check if the authorization was successful or not
if (response.status === 'success') {
//do login here
} else {
//do error here
}
});
});
$(this).serialize() will add the login form's data to the post request. This example assumes your web-service will return JSON.
Have you looked at PhoneGap Plugin: ChildBrowser (iPhone, Android, other) and its locChanged method?
I have only coded apps that use OAuth (Twitter App) and OpenID (AppLaud App) for PhoneGap / Android, but the child browser plugin has what's needed for those. Sounds like Ion Auth may be similar: after auth driven by provider, return user to app seamlessly.