Created
May 23, 2015 07:35
-
-
Save ongspxm/c9994be52c2c5e62bc4d to your computer and use it in GitHub Desktop.
Facebook Authentication using web.py
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
import web | |
import requests | |
client_id = '<client id>' | |
client_secret = '<client secret>' | |
fb_graph = 'https://graph.facebook.com/v2.3/' | |
urls = [ | |
'/', 'Index', | |
'/login', 'Login' | |
] | |
app = web.application(urls, globals()) | |
class Index: | |
def GET(self): | |
i = web.input() | |
if not i.get('access_token'): | |
raise web.seeother('/login') | |
r = requests.get(fb_graph+'me', params={'access_token':i.get('access_token')}).json() | |
return "<html><h3>%s (%s)</h3><img src='%s' /><br/><a href='%s'>View Profile</a></html>"%(r['name'], r['gender'], fb_graph+r['id']+'/picture', r['link']) | |
class Login: | |
def GET(self): | |
i = web.input() | |
uri = web.ctx.realhome+web.ctx.fullpath | |
### TODO: CSRF prevention with state variable | |
if not i.get('code'): | |
raise web.seeother('https://www.facebook.com/dialog/oauth?client_id='+client_id+'&redirect_uri='+uri) | |
r = requests.get(fb_graph+'oauth/access_token', params={ | |
'client_id':client_id, | |
'client_secret':client_secret, | |
'code':i.get('code'), | |
'redirect_uri':uri | |
}) | |
obj = r.json() | |
print obj | |
if obj.get('error'): | |
err = obj['error'] | |
if not err.get('code'): | |
return "<h1 style='color:#F00;'>%s</h1>%s"%(err, obj['error_description']) | |
else: | |
raise web.seeother('/login') | |
raise web.seeother('/?access_token='+obj['access_token']) | |
if __name__=='__main__': | |
app.run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment