Get users's FID, Name and Email after login with Facebook - facebook

I want to get the user's FID, Email and Name after login with Javascript so I make an Ajax call and save them to the database.
This is currently the code to login users:
if (response.status === 'connected') { // the user is logged in and connected to your application
var uid = response.authResponse.userID;
var accessToken = response.authResponse.accessToken;
// Alert with fid, email and name
} else { //the user isn't logged in to Facebook or isn't connected to the application
FB.login(function(response) {
if (response.authResponse) {
accessToken = response.authResponse.accessToken;
// Alert with fid, email and name
}
}, {scope: 'email'});
}
How can I do it?

Call
https://graph.facebook.com/me
or
https://graph.facebook.com/USER_ID
or
https://graph.facebook.com/fql?q=SELECT uid,name,email FROM user WHERE uid=me()
You'll need the
email
permission

Related

appcelerator facebook get username

How can I gett the facebook username of a user via appcelerator facebook login
var fb = require('facebook');
fb.appid = "153xx364563xxxx";
fb.permissions = ['publish_stream']; // Permissions your app needs
fb.forceDialogAuth = true;
fb.addEventListener('login', function(e) {
if (e.success) {
Ti.API.info("Success " + JSON.stringify(e));
alert('Logged In');
} else if (e.error) {
alert(e.error);
} else if (e.cancelled) {
alert("Canceled");
}
});
all I get is the id and name
Success {"success":true,"code":0,"data":"{\"name\":\"John Smith\",\"id\":\"10111182454657222\"}","uid":"10111182454657222","cancelled":false,"bubbles":true,"type":"login","source":{"id":"facebook","appid":"153xx364563xxxx","forceDialogAuth":true},"cancelBubble":false}
The publish_stream permission is deprecated since many years, and there is no way to get the username anymore. The replacement for publish_stream would be publish_actions, but you only need that permission to post to the user wall.
Changelog for v2.0:
/me/username is no longer available.
Source: https://developers.facebook.com/docs/apps/changelog#v2_0
You do not need the username anyway, just use the (App Scoped) ID to identify returning users.

How do I get publish_actions permission with Facebook

I follow a tutor for connection with Facebook which uses the following code to connect to Facebook successfully.
The code follows -
FB.Event.subscribe('auth.authResponseChange', function (response) {
if (response.status === 'connected') {
// the user is logged in and has authenticated your
// app, and response.authResponse supplies
// the user's ID, a valid access token, a signed
// request, and the time the access token
// and signed request each expire
var uid = response.authResponse.userID;
var accessToken = response.authResponse.accessToken;
// TODO: Handle the access token
// Do a post to the server to finish the logon
// This is a form post since we don't want to use AJAX
var form = document.createElement("form");
form.setAttribute("method", 'post');
form.setAttribute("action", 'loadMainPage.ashx');
var field = document.createElement("input");
field.setAttribute("type", "hidden");
field.setAttribute("name", 'accessToken');
field.setAttribute("value", accessToken);
form.appendChild(field);
document.body.appendChild(form);
form.submit();
} else if (response.status === 'not_authorized') {
// the user is logged in to Facebook,
// but has not authenticated your app
} else {
// the user isn't logged in to Facebook.
}
});
};
How can I ask for publish_actions permission ?
What platform are you using? See Facebook's official docs.
An excerpt:
Requesting permissions
Each type of login flow has its own method of requesting these permissions:
Web login with the JavaScript SDK uses a scope option with the FB.login function call.
Other types of web login should add the scope parameter to the Login
dialog URL that they redirect to.
Android login uses the setReadPermissions and setPublishPermissions
on the LoginButton class.
iOS login uses the readPermissions and publishPermissions properties
in the FBLoginView class.

what is response in FB.getLoginStatus

To detect the facebook user online/offline status we use the method FB.getLoginStatus method.
But, what does the paramater("response") mean and where does it come from in the below code snippet
the parameter response mean in the line " FB.getLoginStatus(function(response) "
FB.getLoginStatus(function(response) {
console.log(response);
if (response.status === 'connected') {
// the user is logged in and has authenticated your
// app, and response.authResponse supplies
// the user's ID, a valid access token, a signed
// request, and the time the access token
// and signed request each expire
var uid = response.authResponse.userID;
var accessToken = response.authResponse.accessToken;
console.log('User logged in and autenticated');
} else if (response.status === 'not_authorized') {
// the user is logged in to Facebook,
// but has not authenticated your app
console.log('User logged in, but not autorized');
} else {
// the user isn't logged in to Facebook.
console.log('User not logged in');
}
}, true);
You are specifying a function to be called when the Facebook API has completed retrieving a response from the server. It passes the response object to the function which you specify. A typical response would be:
{
status: 'connected',
authResponse: {
accessToken: '...',
expiresIn:'...',
signedRequest:'...',
userID:'...'
}
}
See facebook javascript docs for more info

FB.getLoginStatus() needs page refreshed

I am using FB.getLoginStatus() and FB.Login() to log the user into my website using facebook. I first check for the status on page load using FB.getLoginStatus() and save the state in a hidden variable. When the user clicks on my facebook login button, I first check the value in the hidden variable and call FB.Login() only if FB.getLoginStatus() is not connected. If FB.getLoginStatus() returns 'Connected', then I just log the user into my website without FB.Login().
My scenario with issue
*user logs into my accont using facebook
*user logs out of my website
*my website is open in the logged out state
*in another tab, the current facebook user logs out of facebook and a new user logs into facebook
*user comes back to my website and clicks on facebook login button without refreshing the page
*the old facebook user (not the one currently logged into facebook) is logged into my account
How can I identify the most current user in facebook when user clicks the facebook login button?
<body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<div id="fb-root">
</div>
<script src="http://connect.facebook.net/en_US/all.js"></script>
<script>
// initialize the library with your Facebook API key
var AppID = '<%=AppID%>';
window.fbAsyncInit = function() {
FB.init({
appId: AppID,
status: true,
cookie: true,
xfbml: true,
channelUrl: 'http://<%=Request.ServerVariables("HTTP_HOST")%>/channel.html'
});
FB.Event.subscribe('auth.login', function(response) {
//alert('logged in');
});
FB.Event.subscribe('auth.logout', function(response) {
//alert('logged out');
});
FB.getLoginStatus(function(response) {
if (response.status === "connected") {
var uid = response.authResponse.userID;
document.getElementById('hdnFBConnected').value = uid;
}
else if (response.status === "not_authorized") {
//alert("Not authorized");
document.getElementById('hdnFBConnected').value = '';
}
else {
//alert("user not logged in to facebook");
document.getElementById('hdnFBConnected').value = '';
}
});
};
</script>
<img src="<%=global_language & "/images/FacebookSmall.gif"%>" />
<script type="text/javascript" language="javascript">
function WindowOpen() {
if (document.getElementById('hdnFBConnected').value != '') //user is connected
{
FB.api('/me', { fields: 'first_name, last_name, locale, email' }, function(result) {
var uid = document.getElementById('hdnFBConnected').value;
//log the user into my site
})
}
else { //user is not connected, so calling FB.Login()
FB.login(function(response) {
if (response.authResponse) {
var access_token = response.authResponse.accessToken;
FB.api('/me', { fields: 'first_name, last_name, locale, email' }, function(result) {
var uid = response.authResponse.userID;
var globalLang = '<%=global_language%>';
//log the user into my site })
}
else {
//alert('User cancelled login or did not fully authorize.');
}
}, { scope: 'email' }
);
}
}
</script>
</body>
What you're describing is normal behavior. The JS SDK is sending the old user's signed_request object which allows the new user to access her account. Since this concerns you, include a logout button on your app's page and let the user know that it's important she clicks that button when she's done using your app. The logout button should call FB.logout like so:
FB.logout(function(response) {
// user is now logged out
});
For extra security, you can create an activity timer that prompts the user to click a button after X minutes of inactivity. If the user doesn't click within, say 1 minute, she is logged out automatically. This is how most banking sites deal with session security.

Facebook Authentication - adding permission for accessing email address

It might be a basic question.
And also my English is poor...
I have a web service which needs Facebook login.
With JavaScript SDK, I can get users' basic information such as user ID, name, gender.
And now there are about 10000 users.
This time, I need to access users' email address.
I know I can get email address from new users by adding scope attribute.
However, from existed users, though I can access email address, I don't know how to display authorization dialogue for permission to access email address.
Any idea? Thanks in advance!
Below is a code snippet that I have used. Basically check their permissions using /me/permissions and show a reauthenticate link
<script>
var FB_config = {
API_ID: 123123123123,
PERMISSIONS: "publish_stream,email",
};
jQuery(document).ready(function(){
// initialise FB
window.fbAsyncInit = function() {
FB.init({
appId : FB_config.API_ID,
status : true,
cookie : true,
xfbml : true,
oauth : true
});
FB.Event.subscribe('auth.statusChange', FBverifyLogin);
};
});
function FBverifyLogin(response) {
if (response.status === 'connected') {
checkPermissions(); // check permissions if the user is logged in
}
}
function checkPermissions(){
jQuery("#FBreauth").hide();
FB.api('/me/permissions', function(response) {
var permissions = FB_config.PERMISSIONS.split(",");
for(var i = 0; i < permissions.length; i++)
{
if(response.data[0][permissions[i]] == undefined || response.data[0][permissions[i]] != 1)
{
// user does not have full permissions, show reauth link
jQuery("#FBreauth").show();
break;
}
}
});
}
function FBreauth(){
FB.ui(
{
method: 'oauth',
display: 'popup',
app_id: FB_config.API_ID,
client_id: FB_config.API_ID,
redirect_uri: "http://www.facebook.com/connect/login_success.html",
scope: FB_config.PERMISSIONS
}
);
}
</script>
App permissions have changes. Please reauthorize this app