Need email perms and user prompted to login despite me not asking? - facebook

I am using the js sdk and getting the basic information such as name, location, id. Great but I need just one more thing and that is email. So I read here that email requires extended permissions. I also read here using fb.login how to ask for extended perms.
In my code from this tutorial here I don't call fb.login yet the visitor gets prompted to login and grant app permissions if they aren't. How is that done? The register button (modified slightly from tutorial) is a div with a class that styles it.
<div class="fb-login-button" data-show-faces="false" data-width="400" data-max-rows="1">Register</div>
Well I inspected the "register" button and found it rendered quite transformed but I never found an onclick or some clue as to how a user clicking on the button event is handled. My GUESS is that the iframe that comes from the styling has a src and the event must be on fb side.
So going back to my script I thought perhaps fb.login was with fb.init and I could add my perm request there but there is no fb.login?? I thought maybe to put it in the else branch below but nothing is there now and it works...minus extended perms for email?
window.fbAsyncInit = function ()
{
FB.init({...removed for concise....});
//If user authorizes using fb account info:
FB.Event.subscribe('auth.authResponseChange', function (response)
{
if (response.status === 'connected')
{
...removed for concise code...
}
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.
//**HERE IS WHERE I WOULD HAVE THOUGHT TO PUT FB.Login**
}
});
};
So what is eluding me is how the pieces fit together in the puzzle. I KNOW I need to ask for extended permissions to get the json to include email but not sure where to make the perm. request at???
This code here is the actual code in the page so you can see my entire sdk implementation.
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function ()
{
FB.init({
appId: 12324, // App ID
status: true, // check login status
cookie: true, // enable cookies
xfbml: true // parse XFBML
});
//If user authorizes using fb account info:
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;
// send access token to server so we can fill in fields
var form = document.createElement("form");
form.setAttribute("method", 'post');
form.setAttribute("action", '/mypage');
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.
}
});
};
// Load the SDK Asynchronously
(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>

Since you are not using the SDK itself to login, but the login button, you have to request the permission via the scope parameter, set as data-scope="…" on the button itself, see https://developers.facebook.com/docs/reference/plugins/login/
The other alternative would be to remove the button, and call FB.login onclick on a button/link of your own making.

Related

how to send uri to facebook in the right format

I need help on facebook login wth app. I have a website http://отдых-сицилия.рф. I did configured this in facebook app, and I am trying to login from my application.
I have the code below:
window.fbAsyncInit = function() {
FB.init({
appId : 'code', // App ID
channelUrl : '//отдых-сицилия.рф/channel.php', // Channel File
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
// Here we subscribe to the auth.authResponseChange JavaScript event. This event is fired
// for any authentication related change, such as login, logout or session refresh. This means that
// whenever someone who was previously logged out tries to log in again, the correct case below
// will be handled.
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.
// FB.login({scope:'email,hometown'});
FB.api('/me', function(response) {
document.getElementById('nome').value = response.name;
if(response.email){
document.getElementById('email').value = response.email;
}
document.getElementById('fbusername').value = response.username;
document.getElementById('fbname').value = response.first_name;
document.getElementById('fbsurname').value = response.last_name;
document.getElementById('nazionalita').value = response.locale;
if(response.hometown){
document.getElementById('citta').value = response.hometown.name;
}
});
} 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.
FB.login({scope:'email,hometown'});
} 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.
FB.login({scope:'email,hometown'});
}
});
};
// Load the SDK asynchronously
(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/it_IT/all.js";
ref.parentNode.insertBefore(js, ref);
}(document));
this code works very good on other 2 websites.
What I noticed is that when I open the login popup, the url is:
redirect_uri=http%3A%2F%2Fwww.facebook.com%2Fdialog%2Freturn%2Farbiter%3Frelation%3Dopener%26close%3Dtrue%23origin%3Dhttp%253A%252F%252F%25D0%25BE%25D1%2582%25D0%25B4%25D1%258B%25D1%2585-%25D1%2581%25D0%25B8%25D1%2586%25D0%25B8%25D0%25BB%25D0%25B8%25D1%258F.%25D1%2580%25D1%2584%252Ff32358e929d241c&app_id={APP_ID}&display=popup
so, the website url is not correct. How can I pass this url correctly?Or what cand I do?
Thank you!

Empty Facebook popup after login

The first time my users accesses the app, everything works fine. The user gets a popup with the question to authorize my app. But then, the next session(ex. refresh), he gets an empty popup that closes itself in an instant.
I believe it's Facebook asking for a new access token, but the problem is that I don't find it user friendly. When a popup opens and closes itself that fast, the user thinks there's something wrong or that he missed something.
Here's the code:
window.fbAsyncInit = function() {
FB.init({
appId : '', // App ID
channelUrl : '', // Channel File
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
// Here we subscribe to the auth.authResponseChange JavaScript event. This event is fired
// for any authentication related change, such as login, logout or session refresh. This means that
// whenever someone who was previously logged out tries to log in again, the correct case below
// will be handled.
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.
if(accessToken)
{
//console.log("Connected WITH accesToken");
testAPI();
}
else{
// console.log("Connected WITHOUTaccesToken");
FB.login(function(response) {
// handle the response
uid = response.authResponse.userID;
accessToken = response.authResponse.accessToken;
//console.log(uid);
//console.log(accessToken);
}, {scope: 'friends_location, user_location, user_relationships'});
}
} 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.
//alert("You're logged in on FB but not on the APP");
FB.login();
} 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.
// FB.login();
//alert("You're offline on FB");
FB.login();
}
});
};
// Load the SDK asynchronously
(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));
// Here we run a very simple test of the Graph API after login is successful.
// This testAPI() function is only called in those cases.
function testAPI() {
FB.api('/'+uid+'/friends?fields=name,location,picture&accesstoken='+accessToken, function(response) {
}
//<img border="0" src="console.log(response.data[0].picture.data.url)">
}
});
}
//Logout
function fbLogout() {
//FB.init();
FB.logout(function (response) {
//Do what ever you want here when logged out like reloading the page
//window.location.reload();
});
}
How can I prevent this empty popup?
You are explicitly calling FB.login, vs FB.getLoginStatus, which is a wrapper around the login dialog. This is why you always get the popup.
Instead, first call getLoginStatus, and only if this fails, you present a button which triggers login.

Requesting Assistance In Getting My Head Around Facebook Login for Websites

I'm wanting to implement the "Login With Facebook" that's common on websites but I'm having trouble grasping the whole concept and if anyone could assist me with this I'd be most appreciative.
I've been reading the documentation under this link https://developers.facebook.com/docs/facebook-login/ for days but I still don't "Get It".
Let's start with...
In the documentation, it says the JS SDK is easiest to use (for whom I dont know) but I'm thinking the NON JS version would be better and faster (and easier for me to grasp) but I don't know what to do. I'm "Stuck"
My main problem is I don't understand how I am suppossed to be able to insert an Auto Incrementing ID along with the person's first and last name into my DB. There's NOTHING or NOWHERE in the Facebook code where I could specify a DB, Table or Column so how is this data suppossed to get into my DB to log the user in??
I have a classifieds on my site of which I'm attempting to create a FB login for but as I said above, I'm stuck and could use help as I have only an intermediate level of knowledge regarding PHP and MySql
Like discussed in comments, here's example using JS SDK
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> <!-- jQuery library, makes things easier. -->
<title>FB example</title>
</head>
<body>
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
// init the FB JS SDK
FB.init({
appId : YOUR_APP_ID, // App ID from the app dashboard
status : true, // Check Facebook Login status
xfbml : true // Look for social plugins on the page
});
// Additional initialization code such as adding Event Listeners goes here
};
// Load the SDK asynchronously
(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 = "//connect.facebook.net/en_US/all.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
/*
This function gets information about user and alrets user's name.
*/
function getUserInfo() {
FB.api('/me', function(response) {
$.ajax({
url: "ajax.php", //url to send ajax request to
data: {
json: response, // Key => value pairs of items to send
},
success: function(ajaxResponse) { // upon successful request
alert(ajaxResponse); //Alert whatever response we got.
}
})
})
}
/*
This function gets the login status of user
*/
function getLoginStatus() {
FB.getLoginStatus(function(response) {
if (response.status === 'connected') { //User is connected to Facebook and authorized your app
getUserInfo();
} else if (response.status === 'not_authorized') { //User is connected to Facebook, but hasn't authorized your app
login();
} else { //User is not connected to Facebook
login();
}
});
}
/*
Function promts user to log in and asks for permissions
*/
function login() {
FB.login(function(response) {
if (response.authResponse) {
getUserInfo();
} else {
alert('User cancelled login or did not fully authorize.');
}
}, {scope: 'email'}); // Comma separated permissions
}
</script>
<a href="javascript:getLoginStatus()"/>Login</a>
</body>
</html>
This is very simple example. On the page you will see link "Login". Upon pressing it you'll be either asked to login (if you're not logged into Facebook, or you haven't authorized app yet), or it will show popup with your name. Most of the code has been taken from JavaScript SDK documentation
EDIT:
To add user's data to your database, i would suggest making AJAX call from the getUserInfo() function. Replace alert part with ajax call to certain php file, which you will create and pass it the data from response variable (which contains data about user, like response.name and response.email). In the php file itself insert the information you got into database.
ANOTHER EDIT:
I've updated the code once again, namely i added jQuery library (easier for me to make ajax calls in it, although it's not much different from plain JS).
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
And updated getUserInfo() function to make ajax request to ajax.php.
In ajax.php i've made only one line:
print_r($_REQUEST['json']);
This will simply print out whatever data was send via ajax, and you will see it in popup. Next step would be checking out what information you get, and take whatever you need (it's $_REQUEST['json'] is simple array), and insert it into db.

How to implement logout with facebook connect in cakephp while preserving facebook login?

how do you logout the user from your site in facebook api, while still keeping the user logged into facebook with cakephp? (I found the answer so wanted to share with everyone).
I figured this one out just now, after reading CakePHP facebook integration logout issue with CakePHP-Facebook-Plugin.
Basically, although in the demos with webtechnick's examples, he puts the "Facebook.Connect" component in the AppController, if you want the selective logout piece, the Best place to put it is in reality within the actual controllers that you want to use it in. That or leave it in AppController and pass noAuth=> true into the Facebook.Connect component.
Either way, whichever way you choose, you set up one controller (facebook_controller.php?) to handle the facebook logins, and set its component with the noauth set to false (which is default, meaning DO authenticate [read connect.php to understand this]). That way, you have total control over when the users are logged into the site, and you can ACTUALLY log them out (with the regular redirect($this->Auth->logout()) without having the connect component immediately log them back in on redirect. Here is an implementation below:
Let me give you an idea:
app_controller.php
class AppController extends Controller {
var $components = array('Auth', 'Acl', 'Session');
//or if you want access to "$this->Connect" universally:
// array('Auth', 'Facebook.Connect' =>
// array('noauth'=>'true'), 'Acl', 'Session');
}
users_controller.php:
class UsersController extends AppController{
var $helpers = array('Facebook.Facebook');
//an example of the users controller, enabling connect, but
// not authorizing the user (because logout() used by Auth is here)
var $components = array('Email', 'Session', 'Facebook.Connect' => array('createUser'=>false, 'noauth'=>true));
//login() doesnt need to be shown and can be left alone for your traditional users
function logout(){
//if there is no fb user, do the logout normal
if ($this->Connect->FB->getUser() == 0){
$this->redirect($this->Auth->logout());
}else{
//ditch FB data for safety
$this->Connect->FB->destroysession();
//hope its all gone with this
session_destroy();
//logout and redirect to the screen that you usually do.
$this->redirect($this->Auth->logout());
}
}
}
your "facebook_controller.php":
class FacebookaController extends AppController {
...
// i dont personally like to have his piece create my user so:
var $components = array('Facebook.Connect' => array('createUser'=>false));
...
function login(){
//just need this stub function for later
$this->autoRender = false;
}
//you also need this for deauths or they will still be able to get into the site after deauth (against policy or whatever)
function deauthorize(){
//get user id from facebook API
$uid = $this->Connect->FB->getUser();
$record = $this->User->findByFacebookId($uid);
$this->User->delete($record['id'], FALSE);
}
}
now your users/login.ctp file:
<script>
window.fbAsyncInit = function() {
FB.init({
appId : 'your app id', // App ID
channelUrl : '//'+window.location.hostname+'/facebook/channel', // Channel File
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
// Additional initialization code here
FB.Event.subscribe('auth.statusChange', function(response){
if (response.status == "connected"){
alert('redirecting you to auto facebook login');
//here is out default place for login
window.location.href = "http://"+window.location.hostname + "/facebook/login";
}
});
};
// Load the SDK Asynchronously
(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>
<?php e($this->Facebook->login(array('registration-url'=>'http://www.yoursite.com/facebook/signup'))); ?>
And that should be pretty much it. I hope this helps someone reading this who still needs the help.

FB undefined while using getLoginStatus in page show

I am getting FB undefined , when i write following code , i have successfully added the necessary files for facebook using window.fbAsyncInit , the thing is if i write following code under "click" event then it works well but not at the time of pageshow in jquery mobile. this is happening might be because the facebook js files are loading bit late. but i want to check the user status on every page to restrict unnecessary or anonymous access.
$("#details").live( "pageshow", function() {
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
// the user is logged in and connected to 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("INSIDE ME");
} else if (response.status === 'not_authorized') {
// the user is logged in to Facebook,
//but not connected to the app
console.log("OUTSIDE ME");
} else {
// the user isn't even logged in to Facebook.
}
});
});
Put the jQuery live() assignment inside the window.fbAsyncInit as well. So that way it is only applied to the DOM element after FB has a chance to initialize.