Facebook JS sdk Oauth onload - facebook-javascript-sdk

I trye to use Facebook JS SDK and I fell on a problem.
I want that after the page load, the user click on the FB button, and then,
if he is already logged I change location,
if not,
it trigger the fb loggin popup
here is my code "
window.fbAsyncInit = function() {
// init the FB JS SDK
FB.init({
appId : '<?php echo $action->appId; ?>', // App ID from the app dashboard
status : true, // Check Facebook Login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // Look for social plugins on the page
});
FB.Event.subscribe('auth.authResponseChange', function(response) {
if (response.status === 'connected') {
$(location).attr('href','nexPage.php');
} else if (response.status === 'not_authorized') {
FB.login();
} else {
FB.login();
}
});
My problem come with the fact that the facebook authResponseChange trigger onload so if the user is already logged and just arrive on the page he is directly send to the next page, and I don't want that !
I want the user to see the page first, click, then login/or not and go to the next page
Does somebody have an idea how to do that ?
(and no click event possible cause after the user logged, FB reload the page)

found !
put the status to false
FB.init({
appId : '<?php echo $action->appId; ?>', // App ID from the app dashboard
status : false, // Check Facebook Login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // Look for social plugins on the page
});
Sorry for disturb

Related

$firebaseSimpleLogin() for facebook doesn't work when preferRedirect is true

Scenario:
Ensure not currently logged into Facebook
Navigate to webapp on localhost
Click "login" and it properly takes you to the Facebook login screen without using a pop-up
Login using valid credentials
Automatically redirect back to localhost
Doesn't appear to be logged in and auth.user is null
Click login again and the request is cancelled automatically by firebase
Navigate to facebook (and may need to refresh) and you are logged in, so the login did "work"
If you use preferRedirect:false the entire scenario works as expected
Versions:
angular and angular-route: 1.3.0-b14
firebase, firebase-simple-login, and angularfire: 1.0.17
Code snippets
/* html snippet */
<div id="login">
<span ng-show="auth.user">
{{auth.user.id}} | Logout
</span>
Login
</div>
/* javascript snippet */
angular.module('<removed_for_this_post>', ['ngRoute', 'firebase'])
.value('firebaseURL', 'https://<removed_for_this_post>.firebaseio.com/')
.factory('FirebaseData', function(firebaseURL) {
return (new Firebase(firebaseURL));
})
.config(function($routeProvider) {
$routeProvider
.when('/', {
controller:'HomeCtrl',
templateUrl:'home.html'
})
.otherwise({
redirectTo:'/'
});
})
.controller('HomeCtrl', function($scope, $firebase, FirebaseData, $firebaseSimpleLogin) {
var ref = new Firebase("https://<removed_for_this_post>.firebaseio.com/");
$scope.auth = $firebaseSimpleLogin(ref);
/* Login using facebook */
$scope.facebookLogin = function() {
$scope.auth.login('facebook', {
rememberMe: true,
preferRedirect: true
});
};
/* Logout using facebook */
$scope.facebookLogout = function() {
$scope.auth.$logout();
};
});
Any thoughts on what I am doing wrong here?
Thanks!

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

getting "Uncaught TypeError: Cannot call method 'replace' of undefined" when doing FB.init using Facebooker2

I am using Facebooker2 to create a Facebook IFrame application, which is running as a tab inside a Facebook page.
My goal is to be able to use the social plugins, such as a like button and comments, etc. I tried to define them as follows
<div class="fb-like" data-href="http://www.myurl.com" data-send="false" data-layout="button_count" data-width="450" data-show-faces="false"></div>
and trying to initialize the FB JS SDK by calling
<%= fb_connect_async_js %>
which outputs
<div id="fb-root"><script async="" src="http://connect.facebook.net/en_US/all.js"></script></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : 'APP_ID',
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
oauth : true,
xfbml : true // parse XFBML
});
};
(function() {
var e = document.createElement('script'); e.async = true;
e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
document.getElementById('fb-root').appendChild(e);
}());
</script>
This has worked before, and stopped working after Facebook pushed their last platform update about a month ago. Now the Like button is not being rendered at all. I also tried the XFBML approach, no luck.
note: I am able to publish feeds using FB.publish, and I am also able to create a like button using the IFrame method.
I looked at the documentation and didn't see anywhere where it was mentioned that Social plugins cannot be used inside IFrame apps.
any ideas anyone?
I've encountered the same issue, and the only workaround i could find is to set a timer to execute FB.XFBML.parse();
If anyone has a better solution, I'd be thanksfull to hear it !
window.fbAsyncInit = function() {
setTimeout(function(){
FB.XFBML.parse();
FB.Event.subscribe('auth.login', function(response) {
fbLogin();
});
FB.Event.subscribe('auth.logout', function(response) {
fbLogout();
});
/* Additional initialization code here */
},
1000);
var params = {
appId : facebookAppId,
channelUrl : siteurl+'facebookChannelFile.php',
status : true,
cookie : true,
oauth : true,
xfbml : true
};
FB.init(params);
};

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.