Skip to content

Commit

Permalink
Enable saving profile information returned by google to be saved to a…
Browse files Browse the repository at this point in the history
… different model
  • Loading branch information
Duncan Morris committed Jan 21, 2015
1 parent 76cf004 commit e39f8bb
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 2 deletions.
24 changes: 23 additions & 1 deletion googleauth/backends.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
import requests
# import requests

from django.conf import settings
from django.db.models import get_model
from django.contrib.auth.models import User, Group

IS_STAFF = getattr(settings, 'GOOGLEAUTH_IS_STAFF', False)
GROUPS = getattr(settings, 'GOOGLEAUTH_GROUPS', tuple())
APPS_DOMAIN = getattr(settings, 'GOOGLEAUTH_APPS_DOMAIN', None)
CLEAN_USERNAME = getattr(settings, 'GOOGLEAUTH_APPS_CLEAN_USERNAME', False)
USERPROFILE_MODEL = getattr(settings, 'GOOGLEAUTH_USERPROFILE_MODEL', None)
PROFILE_FIELDS = getattr(settings, 'GOOGLEAUTH_PROFILE_FIELDS', None)


class GoogleAuthBackend(object):
Expand Down Expand Up @@ -48,10 +52,28 @@ def authenticate(self, identifier=None, attributes=None):

user.save()

if USERPROFILE_MODEL and PROFILE_FIELDS:
model_details = USERPROFILE_MODEL.rsplit('.', 1)

model = get_model(model_details[0], model_details[1])
try:
model.objects.get(user=user)
except model.DoesNotExist:
self.save_user_profile(model, user, attributes)

return user

def get_user(self, user_id):
try:
return User.objects.get(pk=user_id)
except User.DoesNotExist:
pass

def save_user_profile(self, model, user, attributes):

to_save = {'user': user}
for google_field, profile_field in PROFILE_FIELDS.iteritems():
to_save[profile_field] = attributes.get(google_field, None)

userprofile = model(**to_save)
userprofile.save()
8 changes: 7 additions & 1 deletion googleauth/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,9 @@
CALLBACK_DOMAIN = getattr(settings, 'GOOGLEAUTH_CALLBACK_DOMAIN', None)
APPS_DOMAIN = getattr(settings, 'GOOGLEAUTH_APPS_DOMAIN', None)
GET_PROFILE = getattr(settings, 'GOOGLEAUTH_GET_PROFILE', True)
USERPROFILE_MODEL = getattr(settings, 'GOOGLEAUTH_USERPROFILE_MODEL', None)
PROFILE_FIELDS = getattr(settings, 'GOOGLEAUTH_PROFILE_FIELDS', None)


#
# utility methods
Expand Down Expand Up @@ -104,10 +107,13 @@ def callback(request):

profile = resp.json()

if USERPROFILE_MODEL and PROFILE_FIELDS:
for google_field in PROFILE_FIELDS.iterkeys():
attributes[google_field] = profile.get(google_field, None)

attributes['first_name'] = profile.get('given_name')
attributes['last_name'] = profile.get('family_name')


# authenticate user

user = auth.authenticate(attributes=attributes)
Expand Down

0 comments on commit e39f8bb

Please sign in to comment.