I have integrated Facebook login in my website using javascript SDK.. Everything is working fine except for the auth dialog box, which is showing only once for a user.Next time when the user logs it redirects without showing the auth dialog box.I want to show the auth dialog box each time the user logs.
This is the code I am using
window.fbAsyncInit = function() {
FB.init({
appId : 'xxxxxxxx',
status : true,
cookie : true,
xfbml : true,
oauth : true
});
if (window!=window.top) {
FB.Canvas.setAutoResize();
};
FB.getLoginStatus(function(response) {
if (response.authResponse) {
window.FBlogin = function(){
FB.login(function(response) {
if (response.authResponse) {
FB.api('/me', function(response) {
console.log('Good to see you, ' + response.name + '.');
var query = FB.Data.query('select name,username, email, hometown_location, sex, pic_square from user where uid={0}', response.id);
query.wait(function(rows) {
//document.getElementById('name').innerHTML = '<img src="' + rows[0].pic_square + '" alt="" />';
var name=rows[0].name;
var email=rows[0].email;
var uid=response.id;
var username=rows[0].username;
var pic=rows[0].pic_square;
});
});
}
else {
alert("error");
}
}, {scope: 'email'});
};
}
else {
var authbox = document.getElementById('FBauth');
authbox.innerHTML="";
var a = document.createElement('a');
a.setAttribute("href","javascript:void();");
a.setAttribute("onclick","FBlogin();");
authbox.appendChild(a);
window.FBlogin = function(){
FB.login(function(response) {
if (response.authResponse) {
FB.api('/me', function(response) {
console.log('Good to see you, ' + response.name + '.');
var query = FB.Data.query('select name,username, email, hometown_location, sex, pic_square from user where uid={0}', response.id);
query.wait(function(rows) {
var name=rows[0].name;
var email=rows[0].email;
var uid=response.id;
var username=rows[0].username;
var pic=rows[0].pic_square;
});
});
}
}, {scope: 'email'});
};
}
});
FB.Event.subscribe('auth.login', function () {
FB.api('/me', function(response) {
console.log('Good to see you, ' + response.name + '.');
var query = FB.Data.query('select name,username,email, hometown_location, sex, pic_square from user where uid={0}', response.id);
query.wait(function(rows) {
var name=rows[0].name;
var uid=response.id;
var email=rows[0].email;
var username=rows[0].username;
var pic=rows[0].pic_square;
var page='';
$('<input />').attr({'type':'hidden', 'id':'fbname','value':email}).appendTo('#fbaccess');
});
})
});
FB.Event.subscribe('auth.logout', function(response) {
});
};
Everything is working fine except for the auth dialog box, which is showing only once for a user.Next time when the user logs it redirects without showing the auth dialog box.
If the user is already connected to your app and has given all of the requested permissions – then this is the intended behavior.
Calling FB.login again in this situation will open the popup, and close it again immediately.
I want to show the auth dialog box each time the user logs.
I can’t see the benefit of an app behaving in such a way.
Anyways, there is a parameter to explicitly request that the user re-authenticate: auth_type=reauthenticate. This will force the user to re-enter their password. See https://developers.facebook.com/docs/authentication/reauthentication/#client-side for details.
But I’m not sure that this is what you actually want.
Another way could be to delete permissions via your app, and then have them requested again via the scope parameter. That should bring up the Auth dialog again. For details on that, see https://developers.facebook.com/docs/reference/api/user/#permissions
Related
I am already using this script but I didn't get hometown and location when I use API the hometown and location is undefined message appears please give example code and how to get user mobile number in Facebook API:
function login() {
FB.login(function(response) {
if (response.authResponse) {
// connected
testAPI();
} else {
// cancelled
}
}, { scope: 'email,user_birthday,user_location,user_hometown' });
}
function testAPI() {
console.log('Welcome! Fetching your information.... ');
FB.api('/me', function(response) {
console.log('Good to see you, ' + response.name + '.' + ' Email: ' + response.email + ' Facebook ID: ' + response.id);
//console.log('Good to see you, ' + response.name + '.');
var userfirstName=response.first_name;
var lastName=response.last_name;
var useremail=response.email;
var usersex=response.gender;
var userbithday=response.birthday;
var hometown= response.hometown.name;
var location= response.location.name;
alert(hometown);
});
}
<fb:login-button show-faces="false" width="200" max-rows="1" scope="email,user_birthday,user_location,user_hometown" onclick="testAPI();" onlogin="Log.info('onlogin callback')">
Sign Up with Facebook
</fb:login-button>
but can't get hometown and location, please help give any example.
You are using wrong permissions, try this:
{ scope: 'email,user_birthday,user_location,user_hometown' }
Another thing, to access the hometown use this:
var hometown= response.hometown.name;
Also, instead of /me; mention explicitly the fields you want using the fields parameter; just like: /me?fields=hometown
Graph API Explorer
Hey so I am having a hard time understanding how to retrieve data from a user who logs in to my site, I am currently using the javascript sdk but I am trying to figure out how to request the user's data correctly and then how to send it to my server side... I thought it might be something like
req.body.id
for the facebook user id, but I do not think that is it...
Here is the javascript code on my login page.
script(src='//connect.facebook.net/en_US/all.js')
div#fb-root
script.
window.fbAsyncInit = function() {
// init the FB JS SDK
FB.init({
appId: 'blank', // App ID from the app dashboard
//channelUrl:'//WWW.YOUR_DOMAIN.COM/channel.html', // Channel file for x-domain comms
status : true, // Check Facebook Login status
xfbml : true, // Look for social plugins on the page
cookie: true
});
};
(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));
function authUser() {
FB.login(checkLoginStatus, {scope:'email, user_likes'});
function checkLoginStatus(response) {
if(response && response.status == 'connected') {
alert('User is authorized');
document.getElementById('loginButton').style.display = 'none';
console.log('Access Token: ' + response.authResponse.accessToken);
var uid = response.authoResponse.userID;
var accessToken = response.authoResponse.accessToken;
testAPI();
getFBData ();
} else {
alert('User is not authorized');
document.getElementById('loginButton').style.display = 'block';
}
}
}
function testAPI() {
console.log('Welcome! Fetching your information.... ');
FB.api('/me', function(response) {
console.log('Good to see you, ' + response.name + '.' + response.id);
});
};
function getFBData () {
FB.api('/me', function(data){
alert(data.first_name + data.last_name + data.id);
})
};
function fbLogout() {
FB.logout(function (response) {
//window.location.replace("http://stackoverflow.com"); is a redirect
window.location.reload();
});
}
div.centerContent
form(method="POST", action="/login")
fieldset
legend Login
input(type="email", name="email", placeholder="Email", maxlength="20", value= "")
br
input(type="password", name="password", id="password", placeholder="Password", maxlength="20", value= "")
br
input.btn.btn-primary(type="submit", name="login", value="Login")
a(href="/")
button.btn(type="button") Cancel
<fb:login-button show-faces="true" width="200" max-rows="1"></fb:login-button>
button#fbLogout(type="button", onclick="fbLogout()") Logout of FB
button#fbLogin(type="button", onclick="authUser()") Login to FB
It is in jade but it should be readable.
Any help or direction on how to actually grab a user's info(in particular I am looking for a profile picture, access token, user id, first and last name)
Thanks.
EDIT:
I am using node.js and mongodb on the backend
There are many issues with your code.
The biggest one I think is that you don't use the reponse inside the callback!
Others are just wrong spelling of variables like authResponse and authoResponse.
Try this:
function authUser() {
FB.login(checkLoginStatus, {scope:'email, user_likes'});
function checkLoginStatus(response) {
if(!response || response.status !== 'connected') {
alert('User is not authorized');
document.getElementById('loginButton').style.display = 'block';
} else {
alert('User is authorized');
document.getElementById('loginButton').style.display = 'none';
console.log('Access Token: ' + response.authResponse.accessToken);
//This has to be in your callback!
var uid = response.authResponse.userID;
var accessToken = response.authResponse.accessToken;
testAPI();
getFBData();
}
}
}
function testAPI() {
console.log('Welcome! Fetching your information.... ');
FB.api('/me', function(response) {
console.log('Good to see you, ' + response.name + '.' + response.id);
});
};
function getFBData () {
FB.api('/me', function(data){
alert(data.first_name + data.last_name + data.id);
})
};
function fbLogout() {
FB.logout(function (response) {
//window.location.replace("http://stackoverflow.com"); is a redirect
window.location.reload();
});
}
The first thing I can tell from your code is that your login function should be made asynchronous like this:
FB.login(function(response) {
var uid = response.authoResponse.userID;
var accessToken = response.authoResponse.accessToken;
}, {scope: 'email,user_likes'});
Also, when you mention that you would like to pass FB user info to the server side, when a user logs in on the client side, the server side information should already be accessible through the FB PHP SDK. The documentation for this can be found here: https://developers.facebook.com/docs/reference/php/
An example of a PHP call that would provide you with the user info on the server is:
$me = $Facebook->api('/me');
I am using Javascript sdk with a facebook app to create login page for user.
FB.login prompts the user to enter facebook username and password. I have saved all the info such as user_id, Access_token, and all info. However, when the user logout. I want to login to facebook without the need to re-enter username and password again. i want to use the user-id and access token to login directly using the javascript API.
Thanks
function updateButton(response) {
button = document.getElementById('fb-auth');
userInfo = document.getElementById('user-info');
testbut = document.getElementById('test');
var rr = getResponse("user_profile.xml");
if(rr != null)
{
response = rr;
}
if (response.authResponse) {alert('me/permissions/?access_token='+
response.authResponse.accessToken);
FB.api('me/permissions/?access_token='+ response.authResponse.accessToken
,function(response)
{
for (var name in response) {
alert(response.data);
}
alert(response);
});
//user is connected
FB.api('/me', function(info) {
login(response, info);
});
button.onclick = function() {
FB.logout(function(response) {
logout(response);
});
};
} else {
//user is not connected
button.innerHTML = 'Login';
button.onclick = function() {
FB.login(function(response) {
if (response.authResponse) {
FB.api('/me', function(info) {
login(response, info);
});
} else {
//user cancelled login or did not grant authorization
showLoader(false);
}
},
{scope:'email,user_birthday,status_update,publish_stream,user_about_me'});
}
}
}
// run for the current status and whenerve it is changed
FB.getLoginStatus(updateButton);
FB.Event.subscribe('auth.statusChange', updateButton);
};
(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);
}());
function login(response, info){
if (response.authResponse) {
ajaxFunction(response);
var accessToken = response.authResponse.accessToken;
userInfo.innerHTML = '<img src="https://graph.facebook.com/' + info.id
+ "<br /> Your Access Token: " + accessToken;
button.innerHTML = 'Logout';
document.getElementById('other').style.display = "block";
}
}
function logout(response){
userInfo.innerHTML = "";
document.getElementById('debug').innerHTML = "";
document.getElementById('other').style.display = "none";
}
You have to store User access token in your database to user for next time.
Here is some small hint to pass access token using javascript sdk
FB.api('me/permissions/?access_token=Your access token',function(response){console.log(response)});
Chiming in a bit late, but my guess is you are trying to login using an expired or invalidated short-term access token. For future logins, you should convert the short-term access token to a long-term access token, good for about 60 days. The conversion to a long-term token needs to happen on your server as it requires your app-secret. Details are here. The long-term token is what you should be storing in your database (or similar) for future use.
In this script
function fql(){
FB.api('/me', function(response) {
var query = FB.Data.query('select uid, name, email from user where uid={0}', response.id);
query.wait(function(rows) {
document.getElementById('name').innerHTML =
'Your name: ' + rows[0].name + "<br />" +
+ rows[0].email + "<br />" + rows[0].uid;
});
});
}
Function returns name and pic, but email value is NaN. App requires basic data and email (it was set in app properties/Auth dialog) but i cant get user email.
When I tested this query in Facebook test console, I've got email field with correct value.
Check that in Test Console and on your site you use the same application id and ensure that user have granted the email permission to your application!
This can be done with simple Graph API call:
FB.api('/me/permissions', function(response){
if (response && response.data){
var userPermissions = response.data.shift();
if (userPermissions.email){
alert('User is granted email permission');
} else {
alert('User is NOT granted email permission');
}
} else {
// No response or results from the Graph API
}
});
Couple of things you should be aware of!
FB.Data.* is gone! It's deprecated, undocumented and should not be used anymore! It's just a matter of time for it to disappear from the JavaScript SDK code...
You just doesn't want extra call just to figure the id of current user (most chances that you already have it, just check FB.getUserID()), in FQL use me() to refer to current user.
Rewrite your usage of FB.Data.* and query.wait with:
FB.api('/fql', {q:'YOUR_FQL_QUERY_HERE'}, function(response){
var rows = response.data;
});
In your case same results may be received by Graph API call without usage of FQL:
FB.api('/me', {fields: 'id,name,email'}, function(response){
// response -> {id: UID, name: 'User Name', email: 'user#email.dz'}
console.log(response);
});
I have a javascript function that uses fb.login to retrieve the users info and checks to see if the user likes my fb page. fb.login causes a pop up where the user must click a login button. If the user likes my page i need to first create a cookie then redirect them to the main app:
function checkUser() {
var page_id = "my id goes here"; //
FB.login(function (response) {
if (response.authResponse) {
console.log('Welcome! Fetching your information.... ');
FB.api('/me', function (response) {
var fql_query = "SELECT uid FROM page_fan WHERE page_id = " + page_id + "and uid=" + response.id;
var the_query = FB.Data.query(fql_query);
the_query.wait(function (rows) {
if (rows.length == 1 && rows[0].uid == response.id) {
//$("#container_like").show();/
//set cookie
document.cookie = "fbId=" + response.id;
window.location = "/kisses.aspx";
} else {
$("#likepageholder").show();
//$("#container_notlike").show();
//window.location = "/kisses.aspx";
//and here you could get the content for a non liker in ajax...
}
});
});
} else {
console.log('User cancelled login or did not fully authorize.');
}
});
}
If there a way around using fb.login to do this?
Nope. Unfortunately, you need the user to log in (and grant your app basic permissions [based on the appId you use in FB.init) in order to query the user's likes.
That being said, it looks like your code should work.