'This middleware authenticates the facebook user when
he/she is accessing the app from facebook (not an internal page)
The flow is show below:
if referer is facebook:
it\'s a canvas app and the first hit on the app
If error:
attempt to reauthenticate using authorization dialog
if signed_request not sent or does not have the user_id and the access_token:
user has not authorized app
redirect to authorization dialog
else:
check permissions
if user is authenticated (in django):
check if current facebook user is the same that is authenticated
if not: logout authenticated user
if user is not authenticated:
connect_user (django_facebook.connect module)
changed method to GET. Facebook always sends a POST first.
else:
It\'s an internal page.
No signed_request is sent.
Return'

def process_request(self, request):

    redirect_login_oauth = ScriptRedirect(redirect_to=generate_oauth_url(), show_body=False)
    referer = request.META.get('HTTP_REFERER', None)
    if referer:
        urlparsed = urlparse(referer)
        is_facebook = urlparsed.netloc.endswith('facebook.com')
        if (is_facebook and urlparsed.path.endswith('/l.php')):
            return
        if (not is_facebook):
            return
        if ('error' in request.GET):
            return redirect_login_oauth
    else:
        return
    signed_request = request.POST.get('signed_request', None)
    try:
        parsed_signed_request = FacebookAuthorization.parse_signed_data(signed_request)
        access_token = parsed_signed_request['oauth_token']
        if six.PY2:
            facebook_id = long(parsed_signed_request['user_id'])
        else:
            facebook_id = int(parsed_signed_request['user_id'])
    except:
        return redirect_login_oauth
    try:
        graph = self.check_permissions(access_token)
    except MissingPermissionsError:
        return redirect_login_oauth
    if request.user.is_authenticated():
        self.check_django_facebook_user(request, facebook_id, access_token)
    request.facebook = graph
    if (not request.user.is_authenticated()):
        (_action, _user) = connect_user(request, access_token, graph)
    if (request.method == 'POST'):
        request.method = 'GET'
    return
