Middleware to ensure Facebook Auth on all views with Fandjango

Fandjango is a great application for getting a Facebook Canvas application up and running. It provides a nice view decorator to ensure a user is authorised with Facebook before allowing them access to that view. This post provides a piece of middleware that makes use of that decorator, allowing you to enforce Facebook authorisation on all views in your application.

Update

This is an old post. The Facebook API is fundamentally different nowadays so this tip is possibly obsolete.

Fandjango is a brilliant django app that takes the pain out of managing Facebook canvas applications with Django. Once of the nice extras it offers is a decorator to ensure that a user is authorised with Facebook before allowing them access a view. This is very similar to django.contrib.auth's login_required decorator.

But sometimes you want a user to be authorised with Facebook on all pages of your app. It can become tedious having to decorate every view individually. This is a simple piece of middleware to alleviate the problem (here's the Gist):

from django.http import HttpResponseRedirect
from django.conf import settings
from fandjango.decorators import facebook_authorization_required
 
class ExtraFacebookMiddleware:
    """
    An extra layer of middleware on top of Fandjango to
    enforce facebook authentication on every request.
    This avoids having to decorate every view
    """
    def process_view(self, request, view_func, view_args, view_kwargs):
        @facebook_authorization_required(
            permissions=settings.FACEBOOK_APPLICATION_INITIAL_PERMISSIONS)
        def f(request, view_args, view_kwargs):
            return view_func(request, view_args, view_kwargs)
        return f(request, request, view_func, view_args, view_kwargs)

To make use of this middleware simply add it to your settings.py:

settings.py
MIDDLEWARE_CLASSES = (
    #...
    'common.middleware.ExtraFacebookMiddleware'
)