Facebook, Twitter, and other social media websites, also called the new media, are becoming a major part of our culture. Facebook alone has 175 million active users. They are a means to reach broad audiences and build enthousiasm.
This tutorial is part 1 of a series that will focus on connecting your existing web application to Facebook. In this post I’ll show you how to connect Facebook accounts to accounts on your website. This will enable you to update a users status, profile and newsfeed. I’ll be using examples from RepresentMe a project built for the Apps For America contest. This is a standalone webapp that leverages Facebook to deliver its message to a wider audience.
Preparation
Make sure you have the following:
- PyFacebook installed
- An empty Facebook application
- A Django webapp with:
- some form of registration and authentication
- pyfacebook middleware configured
Step 1 – Create Model
We’re going to be linking your website’s accounts to the matching Facebook account. This requires you save the Facebook uid, or user id. The first thing we’ll need is a django model to store this information.
class FacebookLink(models.Model):
"""
Class for holding the infinite session key for the user.
this key is used for automatic updates by repme.org
"""
user = models.ForeignKey(User, unique=True)
facebook_id = models.CharField(max_length=150)
Step 2 – Create A Canvas Handler
Facebook will be making requests to your webapp on behalf of users. We’ll be setting up some view handlers specifically for facebook.
import facebook.djangofb as facebook
@facebook.require_add()
def canvas(request):
"""
Handler for rendering the canvas page for the facebook app
"""
The important part is the @facebook.require_add() decorator. This decorator causes facebook to prompt the user to add your application. Prior to adding your application you will be unable grab much information about the user.
Step 3 – Create URL Mappings
Create your url mappings. You’ll want to pick a base url for your main canvas page. This url will map to the main page displayed for your Facebook app, called the canvas.
http://repme.org/fb/ => http://apps.facebook.com/represent_me/
Facebook allows you to map additional urls but they must be under the original url:
http://repme.org/fb/auth/ => http://apps.facebook.com/represent_me/auth/
Step 4 – Redirecting Unlinked Accounts
For any content that requires a user account you’ll need to make sure the accounts are linked. Facebook recommends that you allow users to try at least part of your application without requiring a login. In this case we’re working with a website that requires registration for most of the content. We’ll be redirecting all unlinked facebook users from the canvas page to an authentication page.
def canvas(request):
...
# Has this user linked their repme account with facebook?
try:
uid = request.facebook.uid
link = FacebookLink.objects.get(facebook_id=uid)
except FacebookLink.DoesNotExist:
# no link object found, redirect to authorization
return HttpResponseRedirect('/facebook/authorize/')
The Facebook middleware will add a facebook object containing some information about the user to the request. request.facebook.uid is the identifier for the Facebook user. If there are no links with that uid then the user has never linked their accounts.
Step 5 – Authorizing The User
We know what Facebook user is requesting pages from request.facebook.uid but they need to prove who they are on our website before we can access their information. We do this by sending them through an authentication process. If they have a valid username and password for an account, they have proven their identity. Once they successfully prove their identity we create and save a new FacebookLink containing their uid.
@facebook.require_add()
def authorize(request):
"""
Form for authorizing a facebook user the first time they add
the app on successful login the facebook uid and session key
will be linked to the account allowing repme.org to send feed
updates on behalf of the user
"""
error = None
try:
# hidden token to ensure form was submitted
request.POST['form_submit']
try:
username = request.POST['username']
password = request.POST['password']
except KeyError:
error = 'Username and Password are required'
raise Exception('breaking out of form processing')
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
# successful login, save facebook info!
link = FacebookLink()
link.user = user
link.facebook_id = request.facebook.uid
link.save()
return HttpResponseRedirect('/facebook/')
else:
error = 'Your account has not been activated'
else:
error = 'Invalid username or password'
except KeyError:
#silently discard form detection
pass
return render_to_response('facebook/login.html', {
'error':error
}, context_instance=RequestContext(request))
Step 6 – The Login Template
The template for the login handler is much like any other django form. There are two differences:
- The form action url must map to the Facebook relative url /represent_me/authorize/
- All requests to handlers are POSTs, we must use a hidden field to detect if the form was actually submitted
<form action=”/represent_me/authorize/” method=”post”>
<input type=”hidden” name=”form_submit” value=”1″>
…
</form>
Step 7 – Displaying The Canvas For Linked Users
We now have the ability to link the account. At this point we can update the canvas handler to render the default view. You can use the FacebookLink object to retrieve the user and any information stored on your website needed for rendering the canvas page.
@facebook.require_add()
def canvas(request):
"""
Handler for rendering the canvas page for the facebook app
"""
#Has this user linked their repme account with facebook?
try:
uid = request.facebook.uid
link = FacebookLink.objects.get(facebook_id=uid)
except FacebookLink.DoesNotExist:
#there was no link object found send user to authorize
return HttpResponseRedirect('/facebook/authorize/')
#user exists, load and render the user specific canvas page
return canvas_lawmakers(request, link)
Wrap Up
The first time a Facebok user visits your Facebook application they will be redirected to an authorization page. The page will identify who they are on your website and save their Facebook uid. The Facebook uid can then be used to look up the user’s account for canvas pages, or used by your webapp to send updates to Facebook.
In part 2 we’ll discuss how to send update to a users Profile, Status, and newsfeed.