Login

Facebook Authentication Backend

Author:
barnardo
Posted:
June 15, 2010
Language:
Python
Version:
1.2
Score:
7 (after 7 ratings)

Authentication through Facebook's Graph API. See

http://developers.facebook.com/docs/authentication/ http://developers.facebook.com/docs/authentication/permissions http://developers.facebook.com/docs/api http://github.com/facebook/python-sdk/blob/master/examples/oauth/facebookoauth.py

Define the facebook tokens in settings.py and replace <app_name> with the name of your app. You will probably want to modify the scope on the authorize link in the template, see the authentication permissions link.</app_name>

This updates the user model every time the user logs in but I think that it is okay so the data is always correct. I have tested this but not rigorously. If there is a hole and everyone gets admin rights to your site don't say I didn't warn you :).

Comments are appreciated.

16 June 2010 Added missing imports. Cleaned up the template.

Shouts out to @obeattie and @whalesalad

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
Settings
---------------------------------------------------------------

FACEBOOK_APP_ID = ''
FACEBOOK_API_KEY = ''
FACEBOOK_API_SECRET = ''
FACEBOOK_REDIRECT_URI = 'http://example.com/login/'

AUTHENTICATION_BACKENDS = (
    '<app_name>.backends.FacebookBackend',
)


Models
----------------------------------------------------------------
from django.db import models
from django.contrib.auth.models import User

class FacebookSessionError(Exception):   
    def __init__(self, error_type, message):
        self.message = message
        self.type = error_type
    def get_message(self): 
        return self.message
    def get_type(self):
        return self.type
    def __unicode__(self):
        return u'%s: "%s"' % (self.type, self.message)
        
class FacebookSession(models.Model):

    access_token = models.CharField(max_length=103, unique=True)
    expires = models.IntegerField(null=True)
        
    user = models.ForeignKey(User, null=True)
    uid = models.BigIntegerField(unique=True, null=True)
        
    class Meta:
        unique_together = (('user', 'uid'), ('access_token', 'expires'))
        
    def query(self, object_id, connection_type=None, metadata=False):
        import urllib
        import simplejson
        
        url = 'https://graph.facebook.com/%s' % (object_id)
        if connection_type:
            url += '/%s' % (connection_type)
        
        params = {'access_token': self.access_token}
        if metadata:
            params['metadata'] = 1
         
        url += '?' + urllib.urlencode(params)
        response = simplejson.load(urllib.urlopen(url))
        if 'error' in response:
            error = response['error']
            raise FacebookSessionError(error['type'], error['message'])
        return response

View
----------------------------------------------------------
from django.contrib import auth
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import RequestContext

import cgi
import simplejson
import urllib

from <app_name> import settings

def login(request):
    error = None

    if request.user.is_authenticated():
        return HttpResponseRedirect('/yay/')

    if request.GET:
        if 'code' in request.GET:
            args = {
                'client_id': settings.FACEBOOK_APP_ID,
                'redirect_uri': settings.FACEBOOK_REDIRECT_URI,
                'client_secret': settings.FACEBOOK_API_SECRET,
                'code': request.GET['code'],
            }

            url = 'https://graph.facebook.com/oauth/access_token?' + \
                    urllib.urlencode(args)
            response = cgi.parse_qs(urllib.urlopen(url).read())
            access_token = response['access_token'][0]
            expires = response['expires'][0]

            facebook_session = models.FacebookSession.objects.get_or_create(
                access_token=access_token,
            )[0]

            facebook_session.expires = expires
            facebook_session.save()

            user = auth.authenticate(token=access_token)
            if user:
                if user.is_active:
                    auth.login(request, user)
                    return HttpResponseRedirect('/yay/')
                else:
                    error = 'AUTH_DISABLED'
            else:
                error = 'AUTH_FAILED'
        elif 'error_reason' in request.GET:
            error = 'AUTH_DENIED'

    template_context = {'settings': settings, 'error': error}
    return render_to_response('login.html', template_context, context_instance=RequestContext(request))


Template
------------------------------------------------------------------------

  {% if error %}
      {% if error == 'AUTH_FAILED' %}
          <p>Authentication failed</p>
      {% else %}{% if error == 'AUTH_DISABLED' %}
          <p>Your account is disabled</p>
      {% else %}{% if error == 'AUTH_DENIED' %}
          <p>You did not allow access</p>
       {% endif %}{% endif %}{% endif %}
  {% else %}
    <a href="https://graph.facebook.com/oauth/authorize?client_id={{ settings.FACEBOOK_APP_ID }}&redirect_uri={{ settings.FACEBOOK_REDIRECT_URI }}&scope=publish_stream,email&display=popup">
      <img src="http://developers.facebook.com/images/devsite/login-button.png"/>
    </a>
  {% endif %}

backends.py                                                                                         ------------------------------------------------------
        
from django.conf import settings
from django.contrib.auth import models as auth_models
    
import cgi
import urllib
import simplejson 

from <app_name> import models

class FacebookBackend:
    
    def authenticate(self, token=None):

        facebook_session = models.FacebookSession.objects.get(
            access_token=token,
        )

        profile = facebook_session.query('me')
   
        try:
            user = auth_models.User.objects.get(username=profile['id'])
        except auth_models.User.DoesNotExist, e:
            user = auth_models.User(username=profile['id'])
    
        user.set_unusable_password()
        user.email = profile['email']
        user.first_name = profile['first_name']
        user.last_name = profile['last_name']
        user.save()

        try:
            models.FacebookSession.objects.get(uid=profile['id']).delete()
        except models.FacebookSession.DoesNotExist, e:
            pass

        facebook_session.uid = profile['id']
        facebook_session.user = user
        facebook_session.save()
   
        return user
   
    def get_user(self, user_id):

        try:
            return auth_models.User.objects.get(pk=user_id)
        except auth_models.User.DoesNotExist:
            return None

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

brooks_lt (on June 15, 2010):

I think you're missing some imports in the "views" section.

#

barnardo (on June 16, 2010):

Thanks, I added them.

#

Upas (on July 13, 2010):

I just wanted to say that I'm using this and it's awesome :D

#

lightcatcher (on July 19, 2010):

very nice code, I'll probably be using that in my next facebook app, I don't know how well (or if) this can work with Google App Engine.

Leveraging the official facebook API code would be good though

#

barnardo (on July 22, 2010):

Graph is now the official API. The REST one has been deprecated. Not sure about Google Apps, been meaning to check the out.

#

diehell (on August 17, 2010):

Barnardo,

Im new django using embarking on my first project making an fb app using django. Will use this for my project. Thanks.

How do i get hold of you on help with django & fb??

#

aisay (on August 18, 2011):

Hi all! Here is a security hole in this snippet: user = auth_models.User.objects.get(username=profile['id'])

username=profile['id'] can be existed user with grand access.

I think the best would be write:

user = facebook_session.user or User(username=profile['id'])

Thanks!

#

frantzdyromain (on September 29, 2011):

@aisay I am just picking up on Django how is it a security hole.

#

ethan.l.whitt (on December 3, 2011):

Has anyone tried this with Django 1.3 ?

#

nxvl (on January 9, 2012):

I have, you need to make a small change:

class FacebookBackend: + supports_object_permissions=True + supports_anonymous_user=False

and it will work.

#

nxvl (on January 9, 2012):

Sorry, Markdown failed on me, add this 2 lines to FacebookBackend class:

supports_object_permissions=True 
supports_anonymous_user=False

#

Amit (on September 27, 2012):

Great example for beginners like me. can you submit the client code as well, the request content is not clear to me. e.g. I didn't figure out the request's 'code' field value used in: if 'code' in request.GET: args = { 'client_id': settings.FACEBOOK_APP_ID, 'redirect_uri': settings.FACEBOOK_REDIRECT_URI, 'client_secret': settings.FACEBOOK_API_SECRET, 'code': request.GET['code'], }

10x!

#

Please login first before commenting.