Created
November 17, 2011 19:35
-
-
Save Alexis-D/1374206 to your computer and use it in GitHub Desktop.
Distributed Systems - Tutorial 3 (Facebook/Oauth2)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!doctype html> | |
<html> | |
<!-- Alexis Daboville - 11110651 1 --> | |
<head> | |
<meta charset="utf-8" /> | |
<title>OAuth 2 - Facebook</title> | |
</head> | |
<body> | |
<!-- placeholder for the name of the user --> | |
<div id="greetings"></div> | |
<script> | |
// dead simple format function, allow formatting like: | |
// '{0} * {1} = {2} (base 13!)'.format(6, 9, 42) | |
// → '6 * 9 = 42 (base 13!)' | |
String.prototype.format = function() { | |
// backup the arguments, as the arguments variable will | |
// be different inside the anonymous function below | |
args = arguments; | |
return this.replace(/{(\d+)}/g, function(match, idx) { | |
return args[idx]; | |
}); | |
}; | |
// the callback function called by fb, just say hello | |
// to the user | |
function greetings(user) { | |
document.getElementById('greetings').appendChild( | |
// in a true application should be handle errors gracefully | |
// test if user.name is != from 'undefined' for instance | |
document.createTextNode('Hello {0}!'.format(user.name)) | |
); | |
window.location.hash = '#'; // pretty uri | |
} | |
// if we have the access token | |
if(window.location.hash.length) { | |
var token = window.location.hash.substring(1), // remove the # | |
url = 'https://graph.facebook.com/me?' | |
+ '{0}&callback={1}', | |
script = document.createElement('script'); | |
script.src = url.format(token, 'greetings'); | |
// append the script tag, fb & JSONP will do the rest | |
document.body.appendChild(script); | |
} | |
// the user isn't logged | |
else { | |
var url = 'https://facebook.com/dialog/oauth?' | |
+ 'client_id={0}&redirect_uri={1}&' | |
+ 'response_type=token'; | |
// redirect him to the login page at fb | |
window.location = url.format(274841145891222, window.location); | |
} | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment