I've been trying to use Facebooker2 as a means to login via Facebook in Rails. However, Facebooker2's current_facebook_user function is somehow returning nil even though I'm definitely logged in on Facebook. Any ideas? Thanks!
Here's the gist of my code:
In one of my controllers:
def check_login
if current_facebook_user.nil?
"This always gets returned, even though I'm logged into Facebook."
else
"This never gets run"
end
end
Facebook JS. The line in FB.Event.subscribe('auth.login', function(response) { ... } redirects to the check_login function above.
<script>
window.fbAsyncInit = function() {
FB.init({
appId : '123456789012345',
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
channelUrl : 'true', // add channelURL to avoid IE redirect problems
xfbml : true // parse XFBML
});
FB.Event.subscribe('auth.login', function(response) {
window.location = "http://www.mysite.com/check_login";
});
}; ( function() {
var s = document.createElement('div');
s.setAttribute('id', 'fb-root');
document.documentElement.getElementsByTagName("body")[0].appendChild(s);
var e = document.createElement('script');
e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
e.async = true;
s.appendChild(e);
}());
function logout() {
FB.logout();
window.location = 'http://www.mysite.com/logout';
};
</script>
If you login through your browser using the Facebook JavaScript SDK the users session data is held within the browser. As result your Rails code is unaware of the change in the users state. So you have to explicitly pass valid current user session data back to your server from which you can maintain a valid session server side as well.
For example:
FB.Event.subscribe('auth.login', function(response) {
window.location = "http://www.mysite.com/check_login?session=" + JSON.stringify(response.session);
});
Related
I'm implementing an application using Facebook login as an optional login approach. After the user logged in with the Facebook account, I write the username into a cookie and want to redirect to the index pager of the website. Everything works OK before I put the redirection code into the file. Here is the code. It's in javascript.
$(document).ready( function(){
window.fbAsyncInit = function() {
FB.init({
appId : 'myAppId',
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
FB.Event.subscribe('auth.authResponseChange', function(response) {
if (response.status === 'connected') {
var userName = testAPI(response);
var today = new Date();
var expire = new Date();
expire.setTime(today.getTime() + 3600000*24*30);
document.cookie="138do_uid="+userName+";expires="+expire.toGMTString()+"path=/";
window.location.assign("myWebpage");
} else if (response.status === 'not_authorized') {
FB.login();
} else {
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));
function testAPI(response) {
var myWindow = window.open("","MsgWindow","width=200,height=100");
var userName;
FB.api('/me', function(response) {
userName = response.name;
myWindow.document.write("<p>" + userName + "</p>");
});
return userName;
}
});
Before I added the line "window.location.assign("myWebpage");", the value of response.name is correct and the name is showed correctly in the pop-up window (The pop-up window is for testing). However, if I add the "window.location" line, the value of response.name suddenly becomes "undefined" and it also showed "undefined" in the pop-up window.
Anyone could tell me what the problem is?
Thanks,
Patrick
There are two major parts to this. The first one is your Facebook web app will only work on your domain space. So first I would try redirecting to a page on your domain space.
The second part is every page in you app that you want to use the Facebook API must have a Facebook object built on it and you have to verify that your user is logged in and they have granted your app the correct permissions to run whatever query you choose to run.
If you wish to expand further on the premise of your app I would be glad to help you out more.
I am Trying to set up my website so that when you go onto the login page it checks if a cookie is set and if it is then the login should be automatic - i.e. when this page loads it redirects to "Facebook.ashx" which creates a cookie to remember access token.
However if the cookie is not set then the user has to click on the Login with Facebook button to continue login which then continues to redirect to "Facebook.ashx" as before.
This is my code - at the moment it always logs in once the user has accepted the app and continues to "Facebook.ashx"
<div id="fb-root"></div>
<script type="text/javascript">
window.fbAsyncInit = function () {
FB.init({
appId: 'My_App_ID', // App ID
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.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");
var redirect = "FacebookLogin.ashx?redirect=" + document.getElementById('redirect').innerHTML;
form.setAttribute("method", 'post');
form.setAttribute("action", redirect);
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>
<div class="fb-login-button" scope="email, publish_stream">Login with Facebook</div>
Thanks For any help in advance
auth.authResponseChange will fire on each page load as long as the user is signed in.
What you want to do is to pass the 'known state' from the server to the client and then compare this inside FB.getLoginStatus. If the state has changes (such as the userID), then this constitutes a real login and you redirect to the ashx page to set new cookies.
As a quick example:
Step one - load page, flush empty state (userID = 0)
Step two - execute FB.getLoginStatus, compare authResponse.userID to userID
Step three - since authResponse.userID <> 0, redirect to the page setting the cookies
Step four - load page, flush state (userID = userID from authResponse.userID)
Step five - execute FB.getLoginStatus, compare authResponse.userID to userID, since they match do nothing.
I worked it out - simple fix
If you change the status to false rather than true then it waits for the user to click login and to check if cookie exists just a simple if statement to change the status to true or false like so:
if (document.cookie.indexOf("fb_token") > 0) //user has already logged in with facebook - process should be automatic
var fb_status = true;
else
var fb_status = false;
window.fbAsyncInit = function () {
FB.init({
appId: 'My App ID', // App ID
status: fb_status, // check login status
cookie: true, // enable cookies to allow the server to access the session
xfbml: true // parse XFBML
});
I am currently working in one facebook application which is going to run outside the facebook in one webpage having functionality of like page, but on bases of like i have to redirect page on different pages,
I tried lots of code to check whether user liked page already or not but failed.
So If any one knows how to check this than please help me.
Thanks in advance.
Note : Want to do only using JS SDK not PHP SDK.
To access the like data form facebook you need user_likes permission.
<div id="fb-root">
</div>
var page_id = 'YOUR PAGE / URL ID';
(function() {
var e = document.createElement('script');
e.type = 'text/javascript';
e.src = document.location.protocol +
'//connect.facebook.net/en_US/all.js';
e.async = true;
document.getElementById('fb-root').appendChild(e);
} ());
window.fbAsyncInit = function() {
FB.init({ appId: 'YOUR APP ID', status: true, cookie: true, xfbml: true, oauth: true });
FB.login(function(response) {
if (response.authResponse) {
FB.api('/me/likes/' + page_id, function(api_response) {
try {
if ((api_response.data[0].name) != undefined)
alert(api_response.data[0].name);
else
alert('you are not like this page');
}
catch (e) {
alert('you are not like this page');
}
});
}
}, { scope: 'email,user_likes' });
};
You have to get user_likes permission, and then make a call to the Graph API requesting /me/likes/{facebook_id_of_your_URL}
That call returns a data array with your URL-objects data, or an empty data array if the user hasn’t liked it yet.
I am trying to add Facebook connect on my website but I am experiencing lot of issues since Facebook moved to OAuth 2 protocol.
I would like users log in with their Facebook account and then, I would store their data in my database.
So I am using the Javascript SDK to catch the auth.login event and then redirect to my fb_login method which use Facebook PHP SDK.
But here is my first issue, most of the time, the auth.login event is not catch by the listener and so my method is not called.
Here is my “listener” Javascript code:
<div id="fb-root"></div>
<script type="text/javascript">
window.fbAsyncInit = function() {
FB.init({
appId: '<?php echo $this->config->item('facebook_app_id'); ?>',
status: true,
cookie: true,
xfbml: true,
oauth: true
});
FB.Event.subscribe('auth.login', function(response) {
[removed] = "<?php echo site_url('donateur/fb_signin'); ?>";
});
FB.Event.subscribe('auth.logout', function(response) {
alert("Logout :(");
});
FB.Event.subscribe('auth.authResponseChange', function(response) {
alert('The status of the session is: ' + response.status);
});
};
(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);
}());
I would like to know if anyone has already experience this issue?
Does anybody has a “recent” doc about how to use Facebook connect in CodeIgniter?
http://codeigniter.com/forums/viewthread/189744/
And this: http://www.dannyherran.com/2011/02/facebook-php-sdk-and-codeigniter-for-basic-user-authentication/
I am trying to write a code that checks whether the user is logged in or not,
and found that there is a built-in method in FBJS API, which is called getLoginStatus()
I have implemented it inside of html,
but for some how, alert() inside of the getLoginStatus() is not fired.
I have also tried to add channelUrl at init(),but it still does the same.
Below is the code that I have written.
Can anyone help me with it?
Thanks in advance!
<!-- Initialize FB API for use -->
<div id="fb-root"></div>
<script type="text/javascript">
//var curLoc = window.location;
//var chanURL = curLoc.protocol + "//" + curLoc.hostname + ":" +
//curLoc.port + "/channel.html"
window.fbAsyncInit = function() {
FB.init({appId: '####', status: true, cookie: true, xfbml: true});
FB.getLoginStatus(function(response) {
if (response.session) {
// logged in and connected user, someone you know
alert('logged in');
} else {
// no user session available, someone you dont know
alert('not logged in');
}
});
};
(function() {
var e = document.createElement('script');
e.type = 'text/javascript';
e.src = document.location.protocol +
'//connect.facebook.net/en_US/all.js';
e.async = true;
document.getElementById('fb-root').appendChild(e);
}());
</script>
I had this the other day and the problem was that I was NOT logged in in Facebook AND my App was in Sandbox mode. Maaaaybe it's the same here, longshot but wanted to suggest it anyway.
Note: Comparable combinations that wouldn't work are being logged in in Facebook as a Test user that has no access to the application in question or being logged in in Facebook as a non-test/non-admin user AND having the app in sandbox mode.
BTW. They changed it again.
It is now:
response.authResponse
and not response.session anymore.
I was having the same problem. I was caused by the 'Sandbox Mode' in the FB App settings. When enabled, it won't fire the getLoginStatus() response. Probably because it is unknown if you're actually a registered developer when not logged in.
They changed it. Run console.log on response, and see you need to test as so:
if (response.status=='connected')) {...}
edit: here is most of my login:
<?php
// using Facebook PHP SDK (v.3.1.1)
$facebook = new Facebook(array(
'appId' => APP_ID
'secret' => SECRET
));
// See if there is a user from a cookie
$user = $facebook->getUser();
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
echo '<pre>'.htmlspecialchars(print_r($e, true)).'</pre>';
$user = null;
}
}
?>
and the js in the body:
<div id="fb-root"></div>
<script src="http://connect.facebook.net/en_US/all.js"></script>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : '<?php echo $facebook->getAppId(); ?>',
status : true,
cookie : true,
oauth: true,
channelUrl : MY_CHANNEL_URL,
xfbml : true
});
FB.getLoginStatus(function(response) {
console.log( response );
if ((response.status)&&(response.status=='connected')) {
loadStreamInto ( $("#FBmessages") );
} else {
}
});
};
</script>
I assume you replaced you actual appId with #### in the code you linked. If not, that is your problem.
Assuming you have actually placed your appId in here, it could be related to the fact that you are testing on localhost. I believe that the javascript will not function if the url it is being served from does not match up with the url associated with the app for the given App Id
the response.status=='connected' happens only if you put oauth:true in fb.init
code looks fine to me should work as is not sure why it doesn't work
I'm not saying this would work for you, but I had a similar problem with my deployed app. It worked fine on my localhost but not when deployed to Heroku. I realised that in the Facebook App settings I had the urls all set as local ones - when I changed this to my deployed app url it fixed it.