Login

Google Account authentication

Author:
Hangya
Posted:
September 1, 2010
Language:
Python
Version:
Not specified
Tags:
authentication openid google-account
Score:
3 (after 3 ratings)

Use django_openid_auth from https://launchpad.net/django-openid-auth to authenticate your users with their Google Account.

This snippet will allow your users having a Google Account address as username to log in using it.

 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
# set the following in settings.py:
#
INSTALLED_APPS = ('django_openid_auth', ...) # https://launchpad.net/django-openid-auth
AUTHENTICATION_BACKENDS = ('somewhere.auth.GoogleBackend', ...)
LOGIN_URL = '/login/'
LOGIN_REDIRECT_URL = '/'
LOGOUT_URL = '/logout/'
OPENID_SSO_SERVER_URL = 'https://www.google.com/accounts/o8/id'

# urlconfs needed in urls.py
#
url(r'^login/$', 'django_openid_auth.views.login_begin', name='openid-login'),
url(r'^login-complete/$', 'django_openid_auth.views.login_complete', name='openid-complete'),
url(r'^logout/$', 'django.contrib.auth.views.logout', {'next_page': '/',}, name='logout'),


# And finally, here is auth.py
#
from django.contrib.auth.models import User
from openid.consumer.consumer import SUCCESS
from django.core.mail import mail_admins

class GoogleBackend:

  def authenticate(self, openid_response):
    if openid_response is None:
      return None
    if openid_response.status != SUCCESS:
      return None
    
    google_email = openid_response.getSigned('http://openid.net/srv/ax/1.0', 'value.email')
    google_firstname = openid_response.getSigned('http://openid.net/srv/ax/1.0', 'value.firstname')
    google_lastname = openid_response.getSigned('http://openid.net/srv/ax/1.0', 'value.lastname')
    try:
      user = User.objects.get(username=google_email)
    except User.DoesNotExist:
      # create a new user, or send a message to admins, etc.
      return None

    return user

  def get_user(self, user_id):

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

More like this

  1. Use django-social-auth & Google Accounts for admin login by pmdarrow 2 years, 8 months ago
  2. User activation codes without additional database tables or fields by badzong 2 years, 10 months ago
  3. Require login by url by zbyte64 7 years ago
  4. Using Google Apps Premium infrastructure for user management by tommy 7 years, 1 month ago
  5. Google Contacts API friend finder by dgouldin 7 years, 4 months ago

Comments

natR (on May 13, 2012):

thanks!

#

natR (on May 14, 2012):

I'm receiving the following error (on Google App Engine).

DatabaseError at /login-complete/ This query is not supported by the database.

Any ideas?

#

Please login first before commenting.