Web.py Tutorial – Facebook Authentication

This is a rehash of the old tutorial after the update in the documentation.

Facebook is one of the most widely used authentication system, used especially to reduce the hassle of signing up for a new application. In this tutorial, I will be showing one way to integrating facebook authentication for your typical application.

This tutorial makes use of Facebook’s Graph API instead of the different SDKs. This method will work as long as your client is able to connect to the internet to access the APIs, be it Android, iOS or other platforms.

There are 2 phases to Facebook’s authentication system — creating a session to request an access token, and requesting for an access token. In the first part, a code is return, it is then used to request an access token. The token is used to access the information using Facebook’s Graph’s API.

For the first part, you will redirect the user to the following page: https://www.facebook.com/dialog/oauth using the client_id and redirect_uri.

### Initiate first stage of the process
if not i.get('code'):
   raise web.seeother('https://www.facebook.com/dialog/oauth?client_id='+client_id+'&redirect_uri='+uri)

In the second part, the access_token will be requested from https://graph.facebook.com/v2.3/oauth/access_token. The client_id and client_secret, together with the code will be used to generate the access_token. Because details of the application are required for this process, it is more to do it through the server. For that, we will make use of the python requests library.

r = requests.get(fb_graph+'oauth/access_token', params={

To test if the authentication actually works, we redirect to a site to test the Facebook Graph API. This is where we get the basic profile information about the user and the profile picture.

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'])

For the full web.py application, with the structure of the different pages, visit the gist below.


Web.py Application – FB Authentication

EDIT: There are some updates to the FB documentation, it doesn’t affect the login process a lot, but I decided to rehash this tutorial anyway. Updated tutorial

Access to Github Repository


Facebook authentication is one of the easiest way of authenticating your user without them having to create a full-fledged user profile system. Here is a quick tutorial of how to integrate facebook login with your web.py application.

Here is the basic setup of the application:

import web
import json
import time
import urllib
import urlparse

FB_APP_ID = ''

urls = [
'/', 'Index',
'/li', 'Login',
'/lo', 'Logout'
app = web.application(urls, globals())

def getURL():
return web.ctx.home + web.ctx.fullpath

Logging In

The login stage of the application requires two main stages: the authentication stage and the retrieval of the access token.

In the authentication stage, the user is redirected to http://www.facebook.com/dialog/oauth where they will accept all the permissions that the application will require. What is returned will be the code which will be used to retrieve the access token for that particular session.

In the second stage, the user is redirected to https://graph.facebook.com/oauth/access_token for the access token. The result is read using the parse_qs function from urlparse, where the access token is extracted.

The last stage of the login will be extracting the user information for storage in the cookies. Using the access token, the user’s profile information is retrieved from https://graph.facebook.com/me, where the user id and the user name is stored for display.

class Login:
def GET(self):
i = web.input(code = None)
args = dict(client_id=FB_APP_ID, redirect_uri=getURL())

### Authentication stage
if not i.code:
web.seeother('http://www.facebook.com/dialog/oauth?' + urllib.urlencode(args))

### Access token stage
args['code'] = i.code
args['client_secret'] = FB_APP_SECRET
req = 'https://graph.facebook.com/oauth/access_token?' + urllib.urlencode(args)
res = urlparse.parse_qs(urllib.urlopen(req).read())
tkn = res['access_token'][-1]

### Retrieving profile information
req = 'https://graph.facebook.com/me?' + urllib.urlencode(dict(access_token=tkn))
res = json.load(urllib.urlopen(req))

t = time.time() + 7*86400
web.setcookie('fb_uid', res['id'], t)
web.setcookie('fb_uname', res['name'], t)


Logging Out

Since we are using cookies to store the session details, logging out will just require us to reset the cookies.

class Logout:
def GET(self):
web.setcookie('fb_uid', '', time.time() - 86400)
web.setcookie('fb_uname', '', time.time() - 86400)

Displaying the information

After the user have logged in, some of the user information will be stored in the cookies. We will make use of this by displaying the user’s name and profile picture if he is logged in. We do so by checking the state of the cookie variables fb_uid and fb_uname, if they exist, they will be printed out, else, a login link will be displayed instead.

class Index:
def GET(self):
html = "<a href="/li">FB Login</a>"

uid = web.cookies().get('fb_uid')
uname = web.cookies().get('fb_uname')

if uid and uname:
html = "<img src="https://graph.facebook.com/"+uid+"/picture" alt="" />
<a href="/lo">Logout</a>"

return '''



There you have it, your own web.py application with facebook authentication.

Things to note

  • To integrate a more general form of OAuth system, take a look at the python-oauth2 package
  • Never reveal your app secret and id, you never know who is looking
  • Original inspiration

Access to Github Repository

UserScript – Mass removal of photo tags in FB

After using Facebook for a while, you would realized that you have a huge load of tagged photos. And it is not always a pleasant experience scrolling through all of them. You could make them harder to find by removing all your tags, but it problem is, Facebook doesn’t allow you to easily remove the tags. Solution: you write a script to do it.

After a morning of fiddling around with the interface, this script was created to remove all your tags from the photos. This is a userscript, or geasemonkey script (either way, it means the same thing). You do need some kind of extension for your browser TamperMonkey for Chrome or GreaseMonkey for Firefox, you can use it for other browsers too, but you will need to find your own extension.

Installing the greasemonkey extension can greatly enhance your browsing experience as well, visit to download more amazing scripts.

DO NOTE THAT IT IS IRREVERSIBLE, which means that if you want all the tags back, you gotta tag your own photos one by one.

  • Install the user script
  • Open up this page: https://m.facebook.com/<username&gt;?v=photos&ref=bookmark
  • In Chrome(other broswer works too): open up the javascript console
  • Run the program in the comment block below (Link Generation), all of it
  • Sit back and relax, if you got quite abit of photos, you gotta wait for quite a long time

EDIT: I made some update to the code for the second version to make it much simple to use for larger quantity of photographs.

Here is the script: