Facebook OAuth User Authentication - javascript

So I've been trying to get a webpage to authenticate a user using Facebook OAuth. I've been following Facebook's tutorial on how to do so, and I have everything finished but I can't seem to make it work.
Here is the code...
<html>
<head>
<script src="http://code.jquery.com/jquery-1.8.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
function main(){ // runs all the other methods when needed, and maintains the proper path from making the form to posting to Facebook
//var imageURL = getImageURL();
//$("img[src='" + imageURL + "']").after("</br><form><input type=\"checkbox\" name=\"geo\" value=\"geolocation\"><b>Use Geolocation?</b> </br> <b>Additional Information About the Image: </b> <input type=\"comment\" name=\"cmnt\"></form>");
//alert("Form should have been placed.");
}
function testAPI() {
alert('Welcome! Fetching your information.... ');
FB.api('/me', function(response) {
alert('Good to see you, ' + response.name + '.');
});
}
// This function right now is hard coded to one particular image right now for testing purposes
// Should be coded in the future to return the URL of a long-pressed image
function getImageURL(){
var url = "http://upload.wikimedia.org/wikipedia/commons/thumb/2/21/Solid_black.svg/200px-Solid_black.svg.png";
return url;
}
// Facebook login code
function login() {
FB.login(function(response) {
if (response.authResponse) {
// connected
alert("Running testAPI();");
testAPI();
} else {
alert("Login not complete.");
// canceled
}
});
}
function testAPI() {
alert('Welcome! Fetching your information.... ');
FB.api('/me', function(response) {
alert('Good to see you, ' + response.name + '.');
});
}
</script>
</head>
<body onload="main()">
<div id="fb-root"></div>
<script>
//-----------------------------
// This is an initilization script created by Facebook.
//-----------------------------
window.fbAsyncInit = function() {
alert("Running Facebook init..");
FB.init({
appId : '488272104524396', // App ID
channelUrl : '//t50.novarra.net/channel.html', // Channel File
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
// Additional init code here
FB.getLoginStatus(function(response) {
alert("Getting Login Status..");
if (response.status === 'connected') {
// connected
alert("Response Status: Connected");
$('.fblogincontainer').removeClass('hidden');
testAPI();
} else if (response.status === 'not_authorized') {
alert("Response Status: Not Authorized");
// not_authorized
login();
} else {
alert("Response Status: Other");
// not_logged_in
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>
<b> Page </b>
<img src="http://upload.wikimedia.org/wikipedia/commons/thumb/2/21/Solid_black.svg/200px-Solid_black.svg.png">
<div id="content">
<div class="fblogincontainer hidden">
<div class="fb-login-button">Login to Facebook</div>
</div>
</div>
</body>
</html>
So my problems are that the FB>getLoginStatus doesn't even start. The alerts for it do not pop up.
Additionally the fb-login-button doesn't seem to function. It disappears for me.

Related

How to redirect user after facebook login

I am developing a game which requires user to login and then uses the login details to update the leaderboard. But the problem is that after the user logs in, the login dialog does not get closed automatically and the user is not redirected to the game. Here is the code which is taken from here
window.fbAsyncInit = function() {
FB.init({
appId : 'XXXXXXXXXX',
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) {
shepResponse = response;
// Here we specify what we do with the response anytime this event occurs.
if (response.status === 'connected')
testAPI();
}
else if (response.status === 'not_authorized') {
FB.login();
} else {
FB.login();
}
});
};
(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 = "http://connect.facebook.net/en_US/all.js";
ref.parentNode.insertBefore(js, ref);
}(document));
function testAPI() {
console.log('Welcome! Fetching your information.... ');
FB.api('/me', function(response) {
console.log('Good to see you, ' + response.name + '.');
});
}
try not wrapping FB.Event.subscribe and testAPI() inside the fbAsyncInit function.
Also try auth.statusChange instead of auth.authResponseChange
var fb_handleStatusChange = function(response) {
if (response.authResponse) {
// user logged in
} else {
// not logged in or logged out
}
}
FB.Event.subscribe('auth.statusChange', fb_handleStatusChange);
Also, i think that the login redirect should be to a page that has this code and is listening for status change. I would not redirect back to the same page as the one used for login.

facebook login error FB.login() called before FB.init()

i have a problem with loggin in into facebook i keep getting the error code: FB.login() called before FB.init(). i done various things but keep getting the error.
here's the html code:
<!-- Javascript
=================================================== -->
<script src="//connect.facebook.net/en_US/all.js"></script>
<script src="js/facebook.js"></script>
</head>
<body>
<div id="fb-root"></div>
<script>
var email;
var name;
window.fbAsyncInit = function()
{
FB.init({
appId : '509855929050339', // App ID
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.login', function () {
window.location = "http://webs.hogent.be/~096506gd/home.html";
});
FB.getLoginStatus(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;
window.location = "http://webs.hogent.be/~096506gd/home.html";
} 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="container">
<img class="offset-by-three ten columns margin-top25" src="images/logo.png">
<div class="offset-by-five">
<a class="six columns full-width button margin-top175" href="home.html">
Aanmelden
</a>
<a class="six columns full-width button margin-top175" onclick="loginUser()">
Aanmelden met facebook
</a>
</div>
</div>
</body>
</html>
and this is the javascript file:
function loginUser(){
FB.login(function(response) {
if (response.authResponse) {
console.log('Welcome! Fetching your information.... ');
//console.log(response); // dump complete info
access_token = response.authResponse.accessToken; //get access token
user_id = response.authResponse.userID; //get FB UID
FB.api('/me', function(response) {
alert ("email: "+response.email); //get user email
alert ("naam : "+respone.name);
// you can store this data into your database
});
} else {
//user hit cancel button
console.log('User cancelled login or did not fully authorize.');
}
}, {
scope: 'publish_stream,email'
});
}
In your code, you are including the Facebook JavaScript SDK three times! Remove the following lines:
<script src="//connect.facebook.net/en_US/all.js"></script>
and
<script id="facebook-jssdk" async="" src="//connect.facebook.net/en_US/all.js"></script>
Also, you may need to wait a second or two before Facebook is initialised, which could be another reason why you were getting the error.
Give it another go and hopefully it will work now.
Just put the app_id next to the js src
<script src="//connect.facebook.net/en_US/all.js&appId=xxxxxxxxxxxxxxx" type="text/javascript"></script>
That worked for me.

Hosting Facebook apps on Dropbox

I'm trying to host a simple JS based Facebook app on dropbox following this question:
Server required for a Facebook application?
Currently I just want to get the login part done before I can continue but i'm having some issues - apparently the call for FB.getLoginStatus doesn't return so the actual login function isn't called.
If I call login() directly (currently commented out) I manage to log into Facebook but then the call FB.api('/me', function(response) {...}) doesn't return so I'm logged in but can't really do anything.
What am I missing? I've set the correct URLs in my Facebook's app page and I really don't know what I'm doing wrong, why does it have to be so hard? :/
Here is my JS code (pretty much copy+paste from Facebook login tutorial) and the HTML is exactly copy+paste from that tutorial.
// Additional JS functions here
function testAPI() {
document.write('Welcome! Fetching your information.... </br>');
FB.api('/me', function(response) {
document.write('Good to see you, ' + response.name + '.</br');
});
}
function login() {
document.write('Logging to Facebook </br>');
FB.login(function(response) {
if (response.authResponse) {
// connected
document.write("User now connected </br>");
testAPI();
} else {
// cancelled
document.write("User cancelled </br>");
}
});
}
window.fbAsyncInit = function() {
document.write("Connecting to facebook </br>");
FB.init({
appId : '542474505763387', // App ID
channelUrl : 'https://dl-web.dropbox.com/get/index.html?w=71a3a216', // Channel File
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
//login();
FB.getLoginStatus(function(response) {
document.write("Response </br>");
if (response.status === 'connected') {
// connected
document.write("connected </br>");
} else if (response.status === 'not_authorized') {
// not_authorized
document.write("not_authorized </br>");
login();
} else {
// not_logged_in
document.write("not_logged_in </br>");
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>

asynchronous facebook functions

I seem to have some issues with the proper order when javascript functions are complete.
I have a page that checks if a user is logged in to facebook or not. If someone is logged in it will logout that person, and redirect to a different page that contains a like button.
However, when I run the webpage without the redirect the user gets logged out properly. If the redirect is inplace, it no longer forces the logout.
You can test the code on this website: http://quiet-depths-9481.herokuapp.com
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML+RDFa 1.0//EN" "http://www.w3.org/MarkUp/DTD/xhtml-rdfa-1.dtd">
<html>
<head>
<script src="src/jquery.js"></script>
</head>
<body style="background-color:#ff6600">
<div id="fb-root"></div>
<script src="http://connect.facebook.net/en_US/all.js#xfbml=1"></script>
<script type="text/javascript">
var loggedout = false;
window.fbAsyncInit = function() {
FB.init({
appId : 'xxxxxxxxxxxxx', // 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
});
fbApiInit = 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/nl_NL/all.js#xfbml=1&appId=511896318825154";
ref.parentNode.insertBefore(js, ref);
}(document));
function fbEnsureInit(callback)
{
if(!window.fbApiInit) {
setTimeout(function() {fbEnsureInit(callback);}, 50);
} else {
if(callback) {
callback();
}
}
}
function fbEnsureLogout(callback)
{
if(!window.loggedout) {
setTimeout(function() {fbEnsureLogout(callback);}, 50);
} else {
if(callback) {
callback();
}
}
}
fbEnsureInit(function()
{
console.log("this will be run once FB is initialized");
checkLogout();
});
fbEnsureLogout(function()
{
console.log("this will run if logout is ensured");
window.location = "http://quiet-depths-9481.herokuapp.com/like.php"
document.write('<div class="fb-like" data-href="https://www.facebook.com/accentjobs" data-width="450" data-show-faces="true" data-stream="true" data-header="true"></div>');
});
function checkLogout()
{
console.log('checkLogout');
FB.getLoginStatus(function(response)
{
if (response.status === 'connected')
{
var uid = response.authResponse.userID;
var accessToken = response.authResponse.accessToken;
console.log('logged in & authenticated');
console.log('trying to logout now.');
FB.logout(function(response)
{
console.log('LOGGED OUT!');
loggedout = true;
});
}
else if (response.status === 'not_authorized')
{
console.log('logged in but no authentication');
console.log('trying to logout now.');
FB.logout(function(response)
{
console.log('LOGGED OUT!');
loggedout = true;
});
}
else
{
console.log('Not logged in to facebook!');
loggedout = true;
}
});
}
</script>
I believe you shouldn't be able to logout facebook users without their authentication with your app. You can read this directly in the console, facebook's all.js returns
FB.logout() called without an access token.
This means, you have to call their api (FB.login or FB.getLoginStatus). Either way, you won't get the access token without proper user authorization with your app/site.
You'll have to make users login with your app and then sign them out. This probably works for you, because you're app owner so basically you're connected via your app.

JavaScript SDK Facebook: Trouble With Init Script

Trying to figure out how to use the JavaScript SDK. I'm new to JavaScrip. I was able to use the PHP SDK but want to run my stuff clientside. Anyhoo, I don't really understand the SDK documentation on the develop site. So the base code is:
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : 'YOUR_APP_ID', // App ID
channelUrl : '//WWW.YOUR_DOMAIN.COM/channel.html', // 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
};
// Load the SDK Asynchronously
(function(d){
var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
d.getElementsByTagName('head')[0].appendChild(js);
}(document));
Which I think I understand...it loads the SDK and then runs the FB.init stuff once it loads. I don't know where to put all of the OAuth stuff though, and how to structure the login request (i.e. if not logged in the make a button and if you are then return access token etc.
Can someone hold my hand through this beginning part. I've searched everywhere and I just don't quite get it.
Edit:
Okay, second try with authentication. Didn't work:
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : 'XXX', // App ID
channelUrl : 'XXX', // 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.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;
FB.api('/me', function(response) {
alert(response.name);
});
} else if (response.status === 'not_authorized') {
FB.login(function(response) {
if (response.authResponse) {
console.log('Welcome! Fetching your information.... ');
FB.api('/me', function(response) {
console.log('Good to see you, ' + response.name + '.');
FB.logout(function(response) {
console.log('Logged out.');
});
});
} else {
console.log('User cancelled login or did not fully authorize.');
}
}, {scope: 'email'});
} else {
}
})
};
// Load the SDK Asynchronously
(function(d){
var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
d.getElementsByTagName('head')[0].appendChild(js);
}(document));
</script>
Thanks!
Just below this line,
// Additional initialization code here
is where the oauth stuff goes.
I would suggest getting used to calling FB.getLoginStatus() first. See: http://developers.facebook.com/docs/reference/javascript/FB.getLoginStatus/
EDIT
based upon the question edit above
This should be done inside the window.fbAsyncInit function
FB.api('/me', function(response) {
alert(response.name);
});
and only after you've checked the getLoginStatus() so you know if the person is logged in or not.

Categories