Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Changes to be compatible with django 1.5. custom user model #180

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion socialregistration/auth.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
from django.contrib.auth.models import User
try:
from django.contrib.auth import get_user_model
User = get_user_model()
except ImportError:
from django.contrib.auth.models import User

from socialregistration.contrib.facebook.auth import FacebookAuth
from socialregistration.contrib.linkedin.auth import LinkedInAuth
from socialregistration.contrib.openid.auth import OpenIDAuth
Expand Down
19 changes: 12 additions & 7 deletions socialregistration/contrib/google/models.py
Original file line number Diff line number Diff line change
@@ -1,35 +1,40 @@
from django.conf import settings
from django.contrib.auth import authenticate
from django.contrib.auth.models import User
from django.contrib.sites.models import Site
from django.db import models
from socialregistration.signals import connect

AUTH_USER_MODEL = getattr(settings, 'AUTH_USER_MODEL', 'auth.User')


class GoogleProfile(models.Model):
user = models.ForeignKey(User, unique=True)
user = models.ForeignKey(AUTH_USER_MODEL, unique=True)
site = models.ForeignKey(Site, default=Site.objects.get_current)
google_id = models.CharField(max_length = 255)
google_id = models.CharField(max_length=255)

def __unicode__(self):
try:
return u'%s: %s' % (self.user, self.google_id)
except User.DoesNotExist:
except models.ObjectDoesNotExist:
return u'None'

def authenticate(self):
return authenticate(google_id=self.google_id)


class GoogleAccessToken(models.Model):
profile = models.OneToOneField(GoogleProfile, related_name='access_token')
access_token = models.CharField(max_length=255)


def save_google_token(sender, user, profile, client, **kwargs):
try:
GoogleAccessToken.objects.get(profile=profile).delete()
except GoogleAccessToken.DoesNotExist:
pass
GoogleAccessToken.objects.create(access_token = client.get_access_token(),
profile = profile)

GoogleAccessToken.objects.create(access_token=client.get_access_token(),
profile=profile)


connect.connect(save_google_token, sender=GoogleProfile,
Expand Down
9 changes: 7 additions & 2 deletions socialregistration/forms.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,16 @@
from django import forms
from django.utils.translation import gettext as _

from django.contrib.auth.models import User
try:
from django.contrib.auth import get_user_model
User = get_user_model()
except ImportError:
from django.contrib.auth.models import User


class UserForm(forms.Form):
"""
Default user creation form. Can be altered with the
Default user creation form. Can be altered with the
`SOCIALREGISTRATION_SETUP_FORM` setting.
"""
username = forms.RegexField(r'^\w+$', max_length=32)
Expand Down
8 changes: 7 additions & 1 deletion socialregistration/mixins.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
from django.conf import settings
from django.contrib.auth import authenticate, login
from django.contrib.auth.models import User
from django.http import HttpResponseRedirect
from django.utils import importlib
from django.utils.translation import ugettext_lazy as _
Expand All @@ -9,9 +8,16 @@
from socialregistration.settings import SESSION_KEY
import urlparse

try:
from django.contrib.auth import get_user_model
User = get_user_model()
except ImportError:
from django.contrib.auth.models import User

ERROR_VIEW = getattr(settings, 'SOCIALREGISTRATION_ERROR_VIEW_FUNCTION',
None)


class CommonMixin(TemplateResponseMixin):
"""
Provides default functionality used such as authenticating and signing
Expand Down
8 changes: 7 additions & 1 deletion socialregistration/tests.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
from django import template
from django.conf import settings
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.test import TestCase
from oauth2 import Client
Expand All @@ -9,6 +8,13 @@
import urllib
import urlparse

try:
from django.contrib.auth import get_user_model
User = get_user_model()
except ImportError:
from django.contrib.auth.models import User


class TemplateTagTest(object):
def get_tag(self):
"""
Expand Down
9 changes: 9 additions & 0 deletions socialregistration/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,12 @@ def generate_username(user, profile, client):
Default function to generate usernames using the built in `uuid` library.
"""
return str(uuid.uuid4())[:30]


def generate_user(request, user, profile, client):
"""
Default function to fill in user attributes
"""
if hasattr(user, "username"):
user.username = generate_username(user, profile, client)
return user, profile
64 changes: 45 additions & 19 deletions socialregistration/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,13 @@
import socket


SEAMLESS_SETUP = getattr(settings, 'SOCIALREGISTRATION_SEAMLESS_SETUP', False)

GENERATE_USERNAME = getattr(settings, 'SOCIALREGISTRATION_GENERATE_USERNAME', False)

USER_FUNCTION = getattr(settings, 'SOCIALREGISTRATION_USER_FUNCTION',
'socialregistration.utils.generate_user')

USERNAME_FUNCTION = getattr(settings, 'SOCIALREGISTRATION_GENERATE_USERNAME_FUNCTION',
'socialregistration.utils.generate_username')

Expand All @@ -32,6 +36,7 @@

logger = logging.getLogger(__name__)


class Setup(SocialRegistration, View):
"""
Setup view to create new Django users from third party APIs.
Expand All @@ -44,14 +49,27 @@ def get_form(self):
with ``SOCIALREGISTRATION_SETUP_FORM``.
"""
return self.import_attribute(FORM_CLASS)
def get_username_function(self):

def get_user_function(self):
"""
Return a function that can generate a username. The function
is controlled with ``SOCIALREGISTRATION_GENERATE_USERNAME_FUNCTION``.
Dispatcher of type of user function.

For SEAMLESS_SETUP it returns a function that can fill necessary fields
in User model. The function have to return tuple (user, profile)
It is controlled with ``SOCIALREGISTRATION_USER_FUNCTION``.

For GENERATE_USERNAME it returns a function that produce unique
username for the new user. The function have to return string - username
It is controlled with ``SOCIALREGISTRATION_GENERATE_USERNAME_FUNCTION``.
"""
return self.import_attribute(USERNAME_FUNCTION)

if SEAMLESS_SETUP:
return self.import_attribute(USER_FUNCTION)
if GENERATE_USERNAME:
return self.import_attribute(USERNAME_FUNCTION)

# DEPRECATED, kept for backward compatibility
get_username_function = get_user_function

def get_initial_data(self, request, user, profile, client):
"""
Return initial data for the setup form. The function can be
Expand Down Expand Up @@ -82,23 +100,28 @@ def get_context(self, request, user, profile, client):
return func(request, user, profile, client)
return {}

def generate_username_and_redirect(self, request, user, profile, client):
def generate_user_and_redirect(self, request, user, profile, client):
"""
Generate a username and then redirect the user to the correct place.
This method is called when ``SOCIALREGISTRATION_GENERATE_USERNAME``
is set.
Fill in user attributes and then redirect the user to the correct place.
This method is called when ``SOCIALREGISTRATION_SEAMLESS_SETUP``
is set.

:param request: The current request object
:param user: The unsaved user object
:param profile: The unsaved profile object
:param client: The API client
"""
func = self.get_username_function()

user.username = func(user, profile, client)
user.set_unusable_password()
user.save()

user_func = self.get_user_function()

if SEAMLESS_SETUP:
user, profile = user_func(request, user, profile, client)
if GENERATE_USERNAME:
user.username = user_func(user, profile, client)

if not user.password:
user.set_unusable_password()
user.save()

profile.user = user
profile.save()

Expand All @@ -113,7 +136,10 @@ def generate_username_and_redirect(self, request, user, profile, client):
self.delete_session_data(request)

return HttpResponseRedirect(self.get_next(request))


# DEPRECATED, kept for backward compatibility
generate_username_and_redirect = generate_user_and_redirect

def get(self, request):
"""
When signing a new user up - either display a setup form, or
Expand All @@ -129,8 +155,8 @@ def get(self, request):
return self.error_to_response(request, dict(
error=_("Social profile is missing from your session.")))

if GENERATE_USERNAME:
return self.generate_username_and_redirect(request, user, profile, client)
if SEAMLESS_SETUP or GENERATE_USERNAME:
return self.generate_user_and_redirect(request, user, profile, client)

form = self.get_form()(initial=self.get_initial_data(request, user, profile, client))

Expand Down