Use user credentials to login to facebook using javascript sdk - javascript

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.

Related

Limiting only specific emails to logIn with Gmail Oauth

I was wondering if I could just simply do the following to limit logins, but I seem to run into a problem where the page just reloads constatly once I log in once.
function onSignIn(googleUser) {
var profile = googleUser.getBasicProfile();
console.log('Name: ' + profile.getName());
console.log('Email: ' + profile.getEmail()); // This is null if the 'email' scope is not present.
//list the emails that can login to the website using Gmail OAuth
if (profile.getEmail() == "XXXXXXXX#gmail.com") {
window.location.href = "./index.html"
} else {
let done = confirm("You don't have permission to access this.")
if (done) {
window.location.href = "https://www.HOMEPAGEco.uk/"
} else {
alert("Please try again.")
}
}
}
The line window.location.href = "./index.html" will always reload the page; if you want no action to be taken when they are in the whitelist, just check if they are NOT in the list.
if (profile.getEmail() !== "XXXXXXXX#gmail.com") {
let done = confirm("You don't have permission to access this.")
if (done) {
window.location.href = "https://www.HOMEPAGEco.uk/"
} else {
alert("Please try again.")
}
}

Retrieve data from facebook api for a user

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

Facebook api work only for me

I'm creating frame app for facebook.
Following code work good for me:
function changeToHome() {
try {
var time = new Date();
FB.api("/me", {fields: "id,first_name,last_name,picture"}, function(response)
{
window.location = '#home';
var fname = encodeURIComponent(response.first_name);
var lname = encodeURIComponent(response.last_name);
var avatar = encodeURIComponent(response.picture.data.url);
var u = '?useradd='+response.id+"&fn="+fname+"&ln="+lname+"&p="+avatar+"&t="+time.getTime();
document.getElementById('game_frame').src=('drop.html'+u);
$.ajax({
url: 'stat-api.php'+u
}).done(function() {
//alert("done");
});
});
} catch(ex) {
//alert(ex);
}
}
But if i try to test it trought other acounts the facebook api doesn't work( I tried different browsers and got the same result.
Try to enable (or disable) sandbox mode.
Solved! It didn't authenticate my app! It was a reason.
Include folowing in window.fbAsyncInit = function() {...}
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
//var uid = response.authResponse.userID; //FACEBOOK_ID
//var accessToken = response.authResponse.accessToken;/ //ACCESS TOKEN
if (response.authResponse) {
// logged in and connected user, someone you know.
// YOUR CODE HERE
changeToHome()
}
}else {
attemptLogin();
}
});
function attemptLogin(){
FB.login(function(response) {
if (response.authResponse) {
// YOUR CODE HERE
changeToHome()
} else {
//if user didn't logged in or didn't authorize your application
}
}, {scope: 'offline_access,publish_stream,manage_pages,publish_actions,user_games_activity'}); //YOUR PERMISSION
}

Issue in the faceebook auth dialog box

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

facebook javascript sdk - how to check if user likes page without fb.login pop up

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.

Categories

Resources