Browse files

Work in progress

  • Loading branch information...
1 parent 45625a6 commit ffec82982fe3fd6ff032c0f4dc498e5cbeef88f6 @flashingpumpkin committed Sep 29, 2011
View
3 example/urls.py
@@ -6,6 +6,7 @@
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
- url(r'^social/', include('socialregistration.urls')),
+ url(r'^social/', include('socialregistration.urls',
+ namespace='socialregistration')),
url(r'^$', 'example.app.views.index', name='index'),
)
View
0 socialregistration/contrib/__init__.py
No changes.
View
0 socialregistration/contrib/openid/__init__.py
No changes.
View
43 socialregistration/contrib/openid/client.py
@@ -0,0 +1,43 @@
+from django.contrib.sites.models import Site
+from django.core.urlresolvers import reverse
+from openid.consumer import consumer
+from socialregistration.client import Client
+from socialregistration.contrib.openid.storage import OpenIDStore
+import urlparse
+
+class OpenIDClient(Client):
+ def init(self, session_data, endpoint_url):
+ self.endpoint_url = endpoint_url
+ self.store = OpenIDStore()
+ self.consumer = consumer.Consumer(session_data, self.store)
+
+ def get_realm(self):
+ if self.is_https():
+ return 'https://%s/' % self.realm or Site.objects.get_current().domain
+ return 'http://%s/' % self.realm or Site.objects.get_current().domain
+
+ def get_callback_url(self):
+ return urlparse.urljoin(self.get_realm(),
+ reverse('socialregistration:openid:callback'))
+
+ def get_redirect_url(self):
+ auth_request = self.consumer.begin(self.endpoint_url)
+
+ redirect_url = auth_request.redirectURL(self.get_realm(),
+ self.get_callback_url())
+
+ return redirect_url
+
+ def complete(self, GET, path):
+ self.result = self.consumer.complete(GET, urlparse.urljoin(self.realm(),
+ path))
+
+ def is_valid(self):
+ return self.result.status == consumer.SUCCESS
+
+ def get_identity(self):
+ return self.result.identity_url
+
+ @staticmethod
+ def get_session_key():
+ return 'socialreg:openid'
View
40 socialregistration/contrib/openid/models.py
@@ -0,0 +1,40 @@
+from django.db import models
+from django.contrib.auth.models import User
+from django.contrib.sites.models import Site
+from django.contrib.auth import authenticate
+
+
+class OpenIDProfile(models.Model):
+ user = models.ForeignKey(User, unique=True)
+ site = models.ForeignKey(Site, default=Site.objects.get_current)
+ identity = models.TextField()
+
+ def __unicode__(self):
+ try:
+ return 'OpenID profile for %s, via provider %s' % (self.user, self.identity)
+ except User.DoesNotExist:
+ return 'OpenID profile for None, via provider None'
+
+ def authenticate(self):
+ return authenticate(identity=self.identity)
+
+class OpenIDStore(models.Model):
+ site = models.ForeignKey(Site, default=Site.objects.get_current)
+ server_url = models.CharField(max_length=255)
+ handle = models.CharField(max_length=255)
+ secret = models.TextField()
+ issued = models.IntegerField()
+ lifetime = models.IntegerField()
+ assoc_type = models.TextField()
+
+ def __unicode__(self):
+ return u'OpenID Store %s for %s' % (self.server_url, self.site)
+
+class OpenIDNonce(models.Model):
+ server_url = models.CharField(max_length=255)
+ timestamp = models.IntegerField()
+ salt = models.CharField(max_length=255)
+ date_created = models.DateTimeField(auto_now_add=True)
+
+ def __unicode__(self):
+ return u'OpenID Nonce for %s' % self.server_url
View
73 socialregistration/contrib/openid/storage.py
@@ -0,0 +1,73 @@
+import base64
+from openid.association import Association
+from openid.store.interface import OpenIDStore
+from socialregistration.contrib.openid.models import (OpenIDNonce,
+ OpenIDStore as OpenIDStoreModel)
+
+class OpenIDStore(OpenIDStore):
+ max_nonce_age = 6 * 60 * 60
+
+ def storeAssociation(self, server_url, assoc=None):
+ stored_assoc = OpenIDStoreModel.objects.create(
+ server_url=server_url,
+ handle=assoc.handle,
+ secret=base64.encodestring(assoc.secret),
+ issued=assoc.issued,
+ lifetime=assoc.issued,
+ assoc_type=assoc.assoc_type
+ )
+
+
+ def getAssociation(self, server_url, handle=None):
+ stored_assocs = OpenIDStoreModel.objects.filter(
+ server_url=server_url
+ )
+ if handle:
+ stored_assocs = stored_assocs.filter(handle=handle)
+
+ stored_assocs.order_by('-issued')
+
+ if stored_assocs.count() == 0:
+ return None
+
+ return_val = None
+
+ for stored_assoc in stored_assocs:
+ assoc = Association(
+ stored_assoc.handle, base64.decodestring(stored_assoc.secret),
+ stored_assoc.issued, stored_assoc.lifetime, stored_assoc.assoc_type
+ )
+
+ if assoc.getExpiresIn() == 0:
+ stored_assoc.delete()
+ else:
+ if return_val is None:
+ return_val = assoc
+
+ return return_val
+
+ def removeAssociation(self, server_url, handle):
+ stored_assocs = OpenIDStoreModel.objects.filter(
+ server_url=server_url
+ )
+ if handle:
+ stored_assocs = stored_assocs.filter(handle=handle)
+
+ stored_assocs.delete()
+
+ def useNonce(self, server_url, timestamp, salt):
+ try:
+ nonce = OpenIDNonce.objects.get(
+ server_url=server_url,
+ timestamp=timestamp,
+ salt=salt
+ )
+ except OpenIDNonce.DoesNotExist:
+ nonce = OpenIDNonce.objects.create(
+ server_url=server_url,
+ timestamp=timestamp,
+ salt=salt
+ )
+ return True
+
+ return False
View
17 socialregistration/contrib/openid/tests.py
@@ -0,0 +1,17 @@
+from socialregistration.tests import SocialRegistrationTestCase
+
+class OpenIDTest(SocialRegistrationTestCase):
+
+ def test_should_redirect_to_openid_provider(self):
+ response = self.client.post(self.url('openid:redirect'),
+ {'openid_redirect': 'https://www.google.com/accounts/o8/id'})
+
+ self.assertEqual(302, response.status_code,
+ "OpenIDRedirect returned another status code: %s", response.status_code)
+
+ def test_should_redirect_to_setup_view(self):
+ response = self.client.get(self.url('openid:callback'))
+
+ self.assertEqual(302, response.status_code,
+ "OpendIDCallback returned anoth status code: %s", response.status_code)
+
View
9 socialregistration/contrib/openid/urls.py
@@ -0,0 +1,9 @@
+from django.conf import settings
+from django.conf.urls.defaults import *
+from socialregistration.contrib.openid.views import OpenIDRedirect, \
+ OpenIDCallback
+
+urlpatterns = patterns('',
+ url('^redirect/$', OpenIDRedirect.as_view(), name='redirect'),
+ url('^callback/$', OpenIDCallback.as_view(), name='callback'),
+)
View
81 socialregistration/contrib/openid/views.py
@@ -0,0 +1,81 @@
+from django.core.urlresolvers import reverse
+from django.http import HttpResponseRedirect
+from django.utils.translation import ugettext_lazy as _
+from socialregistration.contrib.openid.client import OpenIDClient
+from socialregistration.contrib.openid.models import OpenIDProfile
+from socialregistration.views import SocialRegistration, ClientMixin, \
+ ProfileMixin
+
+class OpenIDRedirect(ClientMixin, SocialRegistration):
+ client = OpenIDClient
+
+ def post(self, request):
+ request.session['next'] = self.get_next(request)
+
+ # We don't want to pass in the whole session object as this might not
+ # be pickleable depending on what session backend one is using.
+ # See issue #73
+ client = self.get_client()(dict(request.session.items()),
+ request.POST.get('openid_provider'))
+
+ request.session[self.get_client().get_session_key()] = client
+
+ return HttpResponseRedirect(client.get_redirect_url())
+
+class OpenIDCallback(ClientMixin, ProfileMixin, SocialRegistration):
+ template_name = 'socialregistration/openid.html'
+ model = OpenIDProfile
+ client = OpenIDClient
+
+
+ def get(self, request):
+ client = request.session[self.get_client().get_session_key()]
+
+ client.complete(dict(request.GET.items()), request.get_full_path())
+
+ if not client.is_valid():
+ return self.render_to_response(dict(
+ error=_("Unfortunately we couldn't validate your identity.")))
+
+ # Logged in user connecting an account
+ if request.user.is_authenticated():
+ profile, created = self.get_or_create_profile(user=request.user,
+ identity=client.get_identity(), save=True)
+
+ # Profile already existed - just redirect where the user wanted to
+ # go
+ if not created:
+ return self.redirect(request)
+
+ # Profile didn't exist - store the profile, send the connect signal
+ # and redirect where the user wanted to go
+ self.send_connect_signal(request, request.user, profile, client)
+
+ return self.redirect(request)
+
+ # Logged out user - let's see if we've got the identity saved already.
+ # If so - just log the user in. If not, create profile and redirect
+ # to the setup view
+ user = self.authenticate(identity=client.get_identity())
+
+ if user is None:
+ user = self.create_user()
+ profile = self.create_profile(user, identity=client.get_identity())
+
+ self.store_user(user)
+ self.store_profile(profile)
+ self.store_client(client)
+
+ return HttpResponseRedirect(reverse('socialregistration:setup'))
+
+ if not user.is_active:
+ return self.inactive_response()
+
+ self.login(user)
+
+ profile = self.get_profile(user, identity=client.get_identity())
+
+ self.send_login_signal(request, user, profile, client)
+
+ return self.redirect(request)
+
View
6 socialregistration/tests/__init__.py
@@ -1 +1,7 @@
+from django.core.urlresolvers import reverse
+from django.test import TestCase
from socialregistration.tests.templatetags import *
+
+class SocialRegistrationTestCase(TestCase):
+ def url(self, name, *args):
+ return reverse(name, args=args)
View
101 socialregistration/urls.py
@@ -1,98 +1,25 @@
-"""
-
-Updated on 19.12.2009
-
-@author: alen, pinda
-"""
from django.conf import settings
from django.conf.urls.defaults import *
-from socialregistration.utils import OpenID, OAuthClient, OAuthTwitter, OAuthLinkedIn
-
-
-urlpatterns = patterns('',
- url('^setup/$', 'socialregistration.views.setup',
- name='socialregistration_setup'),
-
- url('^logout/$', 'socialregistration.views.logout',
- name='social_logout'),
-)
+urlpatterns = patterns('',)
-# Setup Facebook URLs if there's an API key specified
-if getattr(settings, 'FACEBOOK_API_KEY', None) is not None:
+if 'socialregistration.contrib.openid' in settings.INSTALLED_APPS:
urlpatterns = urlpatterns + patterns('',
- url('^facebook/login/$', 'socialregistration.views.facebook_login',
- name='facebook_login'),
+ url('openid/', include('socialregistration.contrib.openid.urls',
+ namespace='openid')))
- url('^facebook/connect/$', 'socialregistration.views.facebook_connect',
- name='facebook_connect'),
-
- url('^xd_receiver.htm', 'django.views.generic.simple.direct_to_template',
- {'template':'socialregistration/xd_receiver.html'},
- name='facebook_xd_receiver'),
- )
-
-#Setup Twitter URLs if there's an API key specified
-if getattr(settings, 'TWITTER_CONSUMER_KEY', None) is not None:
+if 'socialregistration.contrib.twitter' in settings.INSTALLED_APPS:
urlpatterns = urlpatterns + patterns('',
- url('^twitter/redirect/$', 'socialregistration.views.oauth_redirect',
- dict(
- consumer_key=settings.TWITTER_CONSUMER_KEY,
- secret_key=settings.TWITTER_CONSUMER_SECRET_KEY,
- request_token_url=settings.TWITTER_REQUEST_TOKEN_URL,
- access_token_url=settings.TWITTER_ACCESS_TOKEN_URL,
- authorization_url=settings.TWITTER_AUTHORIZATION_URL,
- callback_url='twitter_callback',
- client_class = OAuthClient
- ),
- name='twitter_redirect'),
+ url('twitter/', include('socialregistration.contrib.twitter.urls',
+ namespace='twitter')))
- url('^twitter/callback/$', 'socialregistration.views.oauth_callback',
- dict(
- consumer_key=settings.TWITTER_CONSUMER_KEY,
- secret_key=settings.TWITTER_CONSUMER_SECRET_KEY,
- request_token_url=settings.TWITTER_REQUEST_TOKEN_URL,
- access_token_url=settings.TWITTER_ACCESS_TOKEN_URL,
- authorization_url=settings.TWITTER_AUTHORIZATION_URL,
- callback_url='twitter',
- client_class = OAuthClient
- ),
- name='twitter_callback'
- ),
- url('^twitter/$', 'socialregistration.views.twitter', {'client_class': OAuthTwitter}, name='twitter'),
- )
-
-#Setup LinkedIn URLs if there's an API key specified
-if getattr(settings, 'LINKEDIN_CONSUMER_KEY', None) is not None:
+if 'socialregistration.contrib.linkedin' in settings.INSTALLED_APPS:
urlpatterns = urlpatterns + patterns('',
- url('^linkedin/redirect/$', 'socialregistration.views.oauth_redirect',
- dict(
- consumer_key=settings.LINKEDIN_CONSUMER_KEY,
- secret_key=settings.LINKEDIN_CONSUMER_SECRET_KEY,
- request_token_url=settings.LINKEDIN_REQUEST_TOKEN_URL,
- access_token_url=settings.LINKEDIN_ACCESS_TOKEN_URL,
- authorization_url=settings.LINKEDIN_AUTHORIZATION_URL,
- callback_url='linkedin_callback',
- client_class = OAuthClient
- ),
- name='linkedin_redirect'),
+ url('twitter/', include('socialregistration.contrib.linkedin.urls',
+ namespace='linkedin')))
- url('^linkedin/callback/$', 'socialregistration.views.oauth_callback',
- dict(
- consumer_key=settings.LINKEDIN_CONSUMER_KEY,
- secret_key=settings.LINKEDIN_CONSUMER_SECRET_KEY,
- request_token_url=settings.LINKEDIN_REQUEST_TOKEN_URL,
- access_token_url=settings.LINKEDIN_ACCESS_TOKEN_URL,
- authorization_url=settings.LINKEDIN_AUTHORIZATION_URL,
- callback_url='linkedin',
- client_class = OAuthClient
- ),
- name='linkedin_callback'
- ),
- url('^linkedin/$', 'socialregistration.views.linkedin', {'client_class': OAuthLinkedIn}, name='linkedin'),
- )
+if 'socialregistration.contrib.facebook' in settings.INSTALLED_APPS:
+ urlpatterns = urlpatterns + patterns('',
+ url('twitter/', include('socialregistration.contrib.facebook.urls',
+ namespace='facebook')))
-urlpatterns = urlpatterns + patterns('',
- url('^openid/redirect/$', 'socialregistration.views.openid_redirect', { 'client_class': OpenID}, name='openid_redirect'),
- url('^openid/callback/$', 'socialregistration.views.openid_callback', { 'client_class': OpenID}, name='openid_callback')
-)
View
35 socialregistration/utils.py
@@ -7,10 +7,26 @@
http://github.com/leah/python-oauth/blob/master/oauth/example/client.py
http://github.com/facebook/tornado/blob/master/tornado/auth.py
"""
-import time
+from django.conf import settings
+from django.contrib.sites.models import Site
+from django.core.urlresolvers import reverse
+from django.http import HttpResponseRedirect
+from django.utils import simplejson
+from django.utils.translation import gettext as _
+from openid.association import Association as OIDAssociation
+from openid.consumer import consumer as openid
+from openid.consumer.discover import DiscoveryFailure
+from openid.store.interface import OpenIDStore as OIDStore
+from socialregistration.models import OpenIDStore as OpenIDStoreModel, \
+ OpenIDNonce
+from urlparse import urlparse
+from xml.dom import minidom
import base64
+import oauth2 as oauth
+import time
import urllib
import urllib2
+import uuid
# parse_qsl was moved from the cgi namespace to urlparse in Python2.6.
# this allows backwards compatibility
@@ -19,26 +35,12 @@
except ImportError:
from cgi import parse_qsl
-from xml.dom import minidom
-import oauth2 as oauth
-from openid.consumer import consumer as openid
-from openid.consumer.discover import DiscoveryFailure
-from openid.store.interface import OpenIDStore as OIDStore
-from openid.association import Association as OIDAssociation
-from django.http import HttpResponseRedirect
-from django.core.urlresolvers import reverse
-from django.utils.translation import gettext as _
-from django.conf import settings
-from django.utils import simplejson
-from django.contrib.sites.models import Site
-from socialregistration.models import OpenIDStore as OpenIDStoreModel, OpenIDNonce
-from urlparse import urlparse
USE_HTTPS = bool(getattr(settings, 'SOCIALREGISTRATION_USE_HTTPS', False))
@@ -48,6 +50,9 @@ def _https():
else:
return ''
+def generate_username(user, profile, client):
+ return str(uuid.uuid4())[:30]
+
class OpenIDStore(OIDStore):
max_nonce_age = 6 * 60 * 60
View
341 socialregistration/views.py
@@ -1,129 +1,240 @@
-import uuid
-
from django.conf import settings
-from django.template import RequestContext
+from django.contrib.auth import login, authenticate, logout as auth_logout
+from django.contrib.auth.models import User
+from django.contrib.sites.models import Site
from django.core.urlresolvers import reverse
+from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
+from django.template import RequestContext
+from django.utils import importlib
from django.utils.translation import gettext as _
-from django.http import HttpResponseRedirect
+from django.views.generic.base import View, TemplateResponseMixin
+from socialregistration import signals
+from socialregistration.forms import UserForm
+from socialregistration.models import FacebookProfile, TwitterProfile, \
+ LinkedInProfile, OpenIDProfile
+from socialregistration.utils import OAuthClient, OAuthTwitter, OpenID, _https, \
+ DiscoveryFailure
+import uuid
+
try:
from django.views.decorators.csrf import csrf_protect
has_csrf = True
except ImportError:
has_csrf = False
-from django.contrib.auth.models import User
-from django.contrib.auth import login, authenticate, logout as auth_logout
-from django.contrib.sites.models import Site
-
-from socialregistration.forms import UserForm
-from socialregistration.utils import (OAuthClient, OAuthTwitter,
- OpenID, _https, DiscoveryFailure)
-from socialregistration.models import FacebookProfile, TwitterProfile, LinkedInProfile, OpenIDProfile
-from socialregistration import signals
-
-
-FB_ERROR = _('We couldn\'t validate your Facebook credentials')
-
-GENERATE_USERNAME = bool(getattr(settings, 'SOCIALREGISTRATION_GENERATE_USERNAME', False))
-
-def _get_next(request):
- """
- Returns a url to redirect to after the login
- """
- if 'next' in request.session:
- next = request.session['next']
- del request.session['next']
- return next
- elif 'next' in request.GET:
- return request.GET.get('next')
- elif 'next' in request.POST:
- return request.POST.get('next')
- else:
- return getattr(settings, 'LOGIN_REDIRECT_URL', '/')
-
-def _login(request, user, profile, client):
- # we need to persist 'next' across the call to login() as
- # it appears to reset the session data.
- next = request.session.get('next')
- login(request, user)
- if next:
- request.session['next'] = next
- signals.login.send(sender = profile.__class__,
- user = user,
- profile = profile,
- client = client)
-
-def _connect(user, profile, client):
- signals.connect.send(sender = profile.__class__,
- user = user,
- profile = profile,
- client = client)
-
-def setup(request, template='socialregistration/setup.html',
- form_class=UserForm, extra_context=dict(), initial=dict()):
- """
- Setup view to create a username & set email address after authentication
- """
- try:
- social_user = request.session['socialregistration_user']
- social_profile = request.session['socialregistration_profile']
- social_client = request.session['socialregistration_client']
- except KeyError:
- return render_to_response(
- template, dict(error=True), context_instance=RequestContext(request))
-
- if GENERATE_USERNAME:
- social_user.username = str(uuid.uuid4())[:30]
- social_user.save()
-
- social_profile.user = social_user
- social_profile.save()
-
- user = social_profile.authenticate()
- else:
- if not request.method == "POST":
- form = form_class(social_user, social_profile, initial=initial)
- extra_context.update({'form': form})
- return render_to_response(template, extra_context,
- context_instance = RequestContext(request))
-
- form = form_class(social_user, social_profile, request.POST, initial=initial)
+SESSION_KEY = getattr(settings, 'SOCIALREGISTRATION_SESSION_KEY', 'socialregistration_')
+GENERATE_USERNAME = getattr(settings, 'SOCIALREGISTRATION_GENERATE_USERNAME', False)
+USERNAME_FUNCTION = getattr(settings, 'SOCIALREGISTRATION_GENERATE_USERNAME_FUNCTION',
+ 'socialregistration.utils.generate_username')
+
+class ClientMixin(object):
+ # The client class we'll be working with
+ client = None
+
+ def get_client(self):
+ if self.client is None:
+ raise AttributeError('`self.client` is `None`')
+ return self.client
+
+class ProfileMixin(object):
+ # The profile model that we'll be working with
+ model = None
+
+ def get_model(self):
+ if self.model is None:
+ raise AttributeError('`self.model` is `None`')
+ return self.model
+
+ def create_user(self):
+ return User()
+
+ def create_profile(self, user, save=False, **kwargs):
+ profile = self.get_model()(user=user, **kwargs)
+
+ if save:
+ profile.save()
+
+ return profile
+
+ def get_profile(self, **kwargs):
+ self.get_model().objects.get(**kwargs)
+
+ def get_or_create_profile(self, user, save=False, **kwargs):
+ try:
+ profile = self.get_model().objects.get(user=user, **kwargs)
+ return profile, False
+ except self.get_model().DoesNotExist:
+ profile = self.create_profile(user, save=save, **kwargs)
+ return profile, True
+
+class SessionMixin(object):
+ def store_profile(self, request, profile):
+ request.session['%sprofile' % SESSION_KEY] = profile
+
+ def store_user(self, request, user):
+ request.session['%suser' % SESSION_KEY] = user
+
+ def store_client(self, request, client):
+ request.session['%sclient' % SESSION_KEY] = client
+
+ def get_session_data(self, request):
+ user = request.session['%s_user' % SESSION_KEY]
+ profile = request.session['%s_profile' % SESSION_KEY]
+ client = request.session['%s_client' % SESSION_KEY]
+ return user, profile, client
+
+ def delete_session_data(self, request):
+ del request.session['%s_user' % SESSION_KEY]
+ del request.session['%s_profile' % SESSION_KEY]
+ del request.session['%s_client' % SESSION_KEY]
+
+class SignalMixin(object):
+ def send_login_signal(self, request, user, profile, client):
+ signals.login.send(sender=profile.__class__, user=user,
+ profile=profile, client=client, request=request)
+
+ def send_connect_signal(self, request, user, profile, client):
+ signals.connect.send(sender=profile.__class__, user=user, profile=profile,
+ client=client, request=request)
+
+class SocialRegistration(TemplateResponseMixin, View):
+ def get_next(self, request):
+ """
+ Returns a url to redirect to after the login
+ """
+ if 'next' in request.session:
+ next = request.session['next']
+ del request.session['next']
+ return next
+ elif 'next' in request.GET:
+ return request.GET.get('next')
+ elif 'next' in request.POST:
+ return request.POST.get('next')
+ else:
+ return getattr(settings, 'LOGIN_REDIRECT_URL', '/')
- if form.is_valid():
- form.save(request = request)
- user = form.profile.authenticate()
+ def authenticate(self, **kwargs):
+ return authenticate(**kwargs)
+
+ def login(self, request, user):
+ return login(request, user)
+
+ def inactive_response(self):
+ return self.render_to_response({
+ 'error': _("This user account is marked as inactive.")})
- else:
- extra_context.update({'form': form})
- return render_to_response(template, extra_context,
- context_instance = RequestContext(request))
+ def redirect(self, request):
+ return HttpResponseRedirect(self.get_next(request))
+
+def Setup(SocialReg):
+ template_name = 'socialregistration/setup.html'
+
+ def get_username_function(self):
+ """
+ Return a function that can generate a username.
+ """
+ module = '.'.join(USERNAME_FUNCTION.split('.')[:-1])
+ function = USERNAME_FUNCTION.split('.')[-1]
+
+ module = importlib.import_module(module)
+
+ return getattr(module, function)
+
+ def get_initial_data(self, request, user, profile, client):
+ """
+ Fetch some initial data for the user setup form.
+ """
+ return {}
- social_client.request = request
-
- # Removing unused bits. It's important to remove the
- # client from the session because the session gets written
- # to the storage on login and the client holds the request,
- # which is going to fail. Might be worth to change the
- # clients to not hold the whole request.
- if 'socialregistration_user' in request.session:
- del request.session['socialregistration_user']
- if 'socialregistration_profile' in request.session:
- del request.session['socialregistration_profile']
- if 'socialregistration_client' in request.session:
- del request.session['socialregistration_client']
-
- _connect(user, social_profile, social_client)
- _login(request, user, social_profile, social_client)
- return HttpResponseRedirect(_get_next(request))
+ def generate_username_and_redirect(self, request, user, profile, client):
+ """
+ Generate a username, save the profile, login and redirect to the next
+ page.
+ """
+ func = self.get_username_function()
+
+ user.username = func(user, profile, client)
+ user.save()
+
+ profile.user = user
+ profile.save()
+
+ user = profile.authenticate()
+
+ self.send_connect_signal(request, user, profile, client)
+
+ self.login(request, user)
+
+ self.send_login_signal(request, user, profile, client)
+
+ self.delete_session_data(request)
+
+ return HttpResponseRedirect(self.get_next(request))
+
+ def get(self, request):
+ try:
+ user, profile, client = self.get_models(request)
+ except KeyError:
+ return self.render_to_response(dict(
+ error=_("A social profile is missing from your session.")))
+
+ if GENERATE_USERNAME:
+ return self.generate_username_and_redirect(user, profile, client)
+
+ form = self.form(initial=self.get_initial(request, user, profile, client))
+
+ return self.render_to_response(dict(form=form))
+
+ def post(self, request):
+ try:
+ user, profile, client = self.get_models(request)
+ except KeyError:
+ return self.render_to_response(dict(
+ error=_("A social profile is missing from your session.")))
+
+ form = self.form(request.POST, initial=self.get_initial(request, user, profile, client))
+
+ if not form.is_valid():
+ return self.render_to_response(dict(form=form))
+
+ (user, profile) = form.save(request)
+
+ user = profile.authenticate()
+
+ self.send_connect_signal(request, user, profile, client)
+
+ self.login(request, user, profile, client)
+
+ self.send_login_signal(request, user, profile, client)
+
+ self.delete_session_data(request)
+
+ return HttpResponseRedirect(self.get_next(request))
+
+class OAuthRedirect(SocialReg):
+ def get(self, request):
+ request.session['next'] = self.get_next(request)
+ client = self.client(request, self.api_key, self.secret_key)
+ request.session[self.client.get_session_key()] = client
+ return HttpResponseRedirect(client.get_redirect_url())
+
+class OAuthCallback(SocialReg):
+ def get(self, request):
+ request.session['next'] = self.get_next(request)
+ client = request.session[self.client.get_session_key()]
+ client.get_auth_token()
+ return HttpResponseRedirect(reverse(self.callback_url))
-if has_csrf:
- setup = csrf_protect(setup)
+
+
+
+
def facebook_login(request, template='socialregistration/facebook.html',
extra_context=dict(), account_inactive_template='socialregistration/account_inactive.html'):
"""
@@ -149,7 +260,7 @@ def facebook_login(request, template='socialregistration/facebook.html',
context_instance=RequestContext(request))
request.facebook.request = request
- _login(request, user, FacebookProfile.objects.get(user = user), request.facebook)
+ _login(request, user, FacebookProfile.objects.get(user=user), request.facebook)
return HttpResponseRedirect(_get_next(request))
@@ -230,7 +341,7 @@ def twitter(request, account_inactive_template='socialregistration/account_inact
context_instance=RequestContext(request)
)
- _login(request, user, TwitterProfile.objects.get(user = user), client)
+ _login(request, user, TwitterProfile.objects.get(user=user), client)
return HttpResponseRedirect(_get_next(request))
@@ -279,13 +390,13 @@ def linkedin(request, account_inactive_template='socialregistration/account_inac
context_instance=RequestContext(request)
)
- _login(request, user, LinkedInProfile.objects.get(user = user), client)
+ _login(request, user, LinkedInProfile.objects.get(user=user), client)
return HttpResponseRedirect(_get_next(request))
def oauth_redirect(request, consumer_key=None, secret_key=None,
request_token_url=None, access_token_url=None, authorization_url=None,
- callback_url=None, parameters=None, client_class = None):
+ callback_url=None, parameters=None, client_class=None):
"""
View to handle the OAuth based authentication redirect to the service provider
"""
@@ -297,7 +408,7 @@ def oauth_redirect(request, consumer_key=None, secret_key=None,
def oauth_callback(request, consumer_key=None, secret_key=None,
request_token_url=None, access_token_url=None, authorization_url=None,
callback_url=None, template='socialregistration/oauthcallback.html',
- extra_context=dict(), parameters=None, client_class = None):
+ extra_context=dict(), parameters=None, client_class=None):
"""
View to handle final steps of OAuth based authentication where the user
gets redirected back to from the service provider
@@ -314,7 +425,7 @@ def oauth_callback(request, consumer_key=None, secret_key=None,
# We're redirecting to the setup view for this oauth service
return HttpResponseRedirect(reverse(client.callback_url))
-def openid_redirect(request, client_class = None):
+def openid_redirect(request, client_class=None):
"""
Redirect the user to the openid provider
"""
@@ -338,7 +449,7 @@ def openid_redirect(request, client_class = None):
def openid_callback(request, template='socialregistration/openid.html',
extra_context=dict(), account_inactive_template='socialregistration/account_inactive.html',
- client_class = None):
+ client_class=None):
"""
Catches the user when he's redirected back from the provider to our site
"""
@@ -383,7 +494,7 @@ def openid_callback(request, template='socialregistration/openid.html',
context_instance=RequestContext(request)
)
- _login(request, user, OpenIDProfile.objects.get(user = user), client)
+ _login(request, user, OpenIDProfile.objects.get(user=user), client)
return HttpResponseRedirect(_get_next(request))
return render_to_response(

0 comments on commit ffec829

Please sign in to comment.