Skip to content

Saleor Core: the high performance, composable, headless commerce API.

Separate email confirmation from social auth

Krzysiek Szularz5d8240e846b9
diff --git a/registration/forms.py b/registration/forms.py
index 0c3214e945..6581a90032 100644
--- a/registration/forms.py
+++ b/registration/forms.py
@@ -1,7 +1,15 @@
from django import forms
-from django.utils.translation import ugettext_lazy as _
-from django.contrib.auth import get_user_model
+from django.contrib.auth import authenticate, get_user_model
from django.contrib.auth.forms import AuthenticationForm, SetPasswordForm
+from django.core.mail.message import EmailMessage
+from django.core.urlresolvers import reverse
+from django.template.loader import render_to_string
+from django.utils.translation import ugettext_lazy as _
+
+from .models import EmailConfirmation, ExternalUserData
+from .utils import get_client_class_for_serivce
+
+import urlparse
User = get_user_model()
@@ -11,19 +19,24 @@ class LoginForm(AuthenticationForm):
username = forms.EmailField(label=_("Email"), max_length=75)
-class EmailForm(forms.Form):
+class RequestEmailConfirmationForm(forms.Form):
email = forms.EmailField()
+ def __init__(self, local_host, data=None):
+ self.local_host = local_host
+ super(RequestEmailConfirmationForm, self).__init__(data)
-class RegisterForm(EmailForm):
-
- def clean_email(self):
- email = self.cleaned_data.get('email')
- if email:
- if User.objects.filter(email=email).exists():
- raise forms.ValidationError('Email already registered.')
- return email
+ def send(self):
+ email = self.cleaned_data['email']
+ request = EmailConfirmation.objects.create(email=email)
+ path = reverse('registration:confirm_email',
+ kwargs={'pk': request.pk,
+ 'token': request.token})
+ context = {'confirmation_url': urlparse.urljoin(self.local_host, path)}
+ msg = render_to_string('registration/email/confirm_email.txt', context)
+ subject = _('Email confirmation')
+ EmailMessage(subject, msg, to=[email]).send()
class NoPasswordForm(forms.Form):
@@ -47,10 +60,42 @@ class EmailConfirmationFormset(object):
else:
return self.set_password_form.is_valid()
- def save(self):
+ def get_authenticated_user(self):
user = self.email_confirmation.get_or_create_user()
self.email_confirmation.delete()
if not self.no_password():
self.set_password_form.user = user
user = self.set_password_form.save()
+ user = authenticate(user=user)
+ return user
+
+
+class OAuth2CallbackForm(forms.Form):
+
+ code = forms.CharField()
+ error_code = forms.CharField(required=False)
+ error_message = forms.CharField(required=False)
+
+ def __init__(self, service, local_host, data):
+ self.service = service
+ self.local_host = local_host
+ super(OAuth2CallbackForm, self).__init__(data)
+
+ def clean_error_message(self):
+ error_message = self.cleaned_data.get('error_message')
+ if error_message:
+ raise forms.ValidationError(error_message)
+
+ def get_authenticated_user(self):
+ code = self.cleaned_data.get('code')
+ client_class = get_client_class_for_serivce(self.service)
+ client = client_class(local_host=self.local_host, code=code)
+ user_info = client.get_user_info()
+ user = authenticate(external_service=self.service,
+ external_username=user_info['id'])
+ if not user:
+ user, _ = User.objects.get_or_create(email=user_info['email'])
+ external_user, _ = ExternalUserData.objects.get_or_create(
+ username=user_info['id'], provider=self.service, user=user)
+ user = authenticate(user=user)
return user
diff --git a/registration/models.py b/registration/models.py
index 4db64b282a..374d6f41d0 100644
--- a/registration/models.py
+++ b/registration/models.py
@@ -37,11 +37,8 @@ class EmailConfirmation(models.Model):
'Confirms that user owns this email address and returns User insatnce'
if self.external_user and self.external_user.user:
return self.external_user.user
-
user, _created = User.objects.get_or_create(email=self.email)
-
if self.external_user:
self.external_user.user = user
self.external_user.save()
-
return user
diff --git a/registration/templates/registration/email/confirm_email_ownership.txt b/registration/templates/registration/email/confirm_email.txt
similarity index 100%
rename from registration/templates/registration/email/confirm_email_ownership.txt
rename to registration/templates/registration/email/confirm_email.txt
diff --git a/registration/templates/registration/login.html b/registration/templates/registration/login.html
index 33f5af4abe..87cb5548e3 100644
--- a/registration/templates/registration/login.html
+++ b/registration/templates/registration/login.html
@@ -32,6 +32,6 @@
</div>
<p>
- <a href="{% url 'registration:register' %}">Create an account or reset password</a>
+ <a href="{% url 'registration:request_email_confirmation' %}">Create an account or reset password</a>
</p>
{% endblock %}
diff --git a/registration/templates/registration/register.html b/registration/templates/registration/register.html
deleted file mode 100644
index 91f82d3c4b..0000000000
--- a/registration/templates/registration/register.html
+++ /dev/null
@@ -1,11 +0,0 @@
-{% extends "base.html" %}
-{% block title %}Register for an account{% endblock %}
-{% block content %}
- <div>
- <form method='post' action='{% url 'registration:register' %}'>
- {% csrf_token %}
- {{ form }}
- <input type="submit" value="Continue">
- </form>
- </div>
-{% endblock %}
diff --git a/registration/templates/registration/request_email_confirmation.html b/registration/templates/registration/request_email_confirmation.html
new file mode 100644
index 0000000000..512a5a65b8
--- /dev/null
+++ b/registration/templates/registration/request_email_confirmation.html
@@ -0,0 +1,14 @@
+{% extends "base.html" %}
+{% load bootstrap %}
+
+{% block title %}Request email confirmation{% endblock %}
+
+{% block content %}
+<div>
+ <form method='post'>
+ {% csrf_token %}
+ {{ form|as_bootstrap }}
+ <input type="submit" value="Continue">
+ </form>
+</div>
+{% endblock %}
diff --git a/registration/urls.py b/registration/urls.py
index 5c0c070413..6750932ef4 100644
--- a/registration/urls.py
+++ b/registration/urls.py
@@ -5,7 +5,9 @@ urlpatterns = patterns(
'',
url(r'^login/$', 'registration.views.login', name='login'),
url(r'^logout/$', 'registration.views.logout', name='logout'),
- url(r'^register/$', 'registration.views.register', name='register'),
+ url(r'^request_email_confirmation/$',
+ 'registration.views.request_email_confirmation',
+ name='request_email_confirmation'),
url(r'^oauth_callback/(?P<service>\w+)/$',
'registration.views.oauth_callback',
name='oauth_callback'),
diff --git a/registration/utils.py b/registration/utils.py
index 927609abe2..f4655e01fd 100644
--- a/registration/utils.py
+++ b/registration/utils.py
@@ -1,100 +1,175 @@
from django.core.urlresolvers import reverse
from django.conf import settings
-from django.template.loader import render_to_string
+from django.contrib.auth import get_user_model
-import facebook
-import httplib2
-import json
-from oauth2client.client import OAuth2WebServerFlow, FlowExchangeError
+import logging
+import requests
+import urllib
+import urlparse
+
+GOOGLE, FACEBOOK = 'google', 'facebook'
+User = get_user_model()
+logger = logging.getLogger('saleor.registration')
def get_protocol_and_host(request):
- return 'http%(secure)s://%(host)s' % {
- 'secure': 's' if request.is_secure() else '',
- 'host': request.get_host()}
+ scheme = 'http' + ('s' if request.is_secure() else '')
+ return url(scheme=scheme, host=request.get_host())
-def get_callback_url(host, **kwargs):
- return host + reverse('registration:oauth_callback', kwargs=kwargs)
+def get_client_class_for_serivce(service):
+ return {GOOGLE: GoogleClient, FACEBOOK: FacebookClient}[service]
-def get_google_flow(local_host, **kwargs):
- return OAuth2WebServerFlow(
- client_id=settings.GOOGLE_CLIENT_ID,
- client_secret=settings.GOOGLE_SECRET,
- redirect_uri=get_callback_url(host=local_host, service='google'),
- scope='https://www.googleapis.com/auth/plus.me '
- 'https://www.googleapis.com/auth/userinfo.email',
- **kwargs)
+def get_google_login_url(local_host):
+ return get_client_class_for_serivce(GOOGLE)(local_host).get_login_uri()
-def get_google_userinfo_url():
- return 'https://www.googleapis.com/oauth2/v1/userinfo'
+def get_facebook_login_url(local_host):
+ return get_client_class_for_serivce(FACEBOOK)(local_host).get_login_uri()
+
+def url(scheme='', host='', path='', params='', query='', fragment=''):
+ return urlparse.urlunparse((scheme, host, path, params, query, fragment))
-def get_google_login_url(local_host):
- return ('https://accounts.google.com/o/oauth2/auth?'
- 'scope=https://www.googleapis.com/auth/userinfo.email+'
- 'https://www.googleapis.com/auth/plus.me'
- '&redirect_uri=%(callback)s'
- '&response_type=code'
- '&client_id=%(client_id)s' % {
- 'callback': get_callback_url(host=local_host, service='google'),
- 'client_id': settings.GOOGLE_CLIENT_ID
- })
-
-
-def google_callback(local_host, data):
- code = data.get('code', '')
- try:
- credentials = get_google_flow(local_host).step2_exchange(code)
- except FlowExchangeError: # TODO: log this
- return None, None
- http = credentials.authorize(httplib2.Http())
- # TODO: some smarter exception handling here
- try:
- _header, content = http.request(get_google_userinfo_url())
- except Exception: # TODO: log this
- return None, None
- google_user_data = json.loads(content)
- external_username = google_user_data['id']
- if not google_user_data.get('verified_email'):
- return '', external_username
- return google_user_data['email'], external_username
+class OAuth2Connection(object):
-def get_facebook_login_url(local_host):
- return facebook.auth_url(settings.FACEBOOK_APP_ID,
- get_callback_url(host=local_host,
- service='facebook'),
- ['email'])
-
-
-def facebook_callback(local_host, data):
- code = data.get('code', '')
- try:
- facebook_auth_data = facebook.get_access_token_from_code(
- code, get_callback_url(host=local_host, service='facebook'),
- settings.FACEBOOK_APP_ID, settings.FACEBOOK_SECRET)
- except Exception: # TODO: log this
- return None, None
-
- graph = facebook.GraphAPI(facebook_auth_data['access_token'])
- try:
- fb_user_data = graph.get_object('me')
- except Exception: # TODO: log this
- return None, None
-
- external_username = fb_user_data.get('id')
- email = fb_user_data.get('email')
-
- return email, external_username
-
-
-def get_email_confirmation_message(local_host, email_confirmation):
- confirmation_url = local_host + reverse(
- 'registration:confirm_email',
- kwargs={'pk': email_confirmation.pk,
- 'token': email_confirmation.token})
- return render_to_string('registration/email/confirm_email_ownership.txt',
- {'confirmation_url': confirmation_url})
+ def __init__(self, code, client):
+ self.code = code
+ self.client = client
+ self.access_token = None
+ self.refresh_token = None
+
+ def get(self, address, params=None, headers=None, auth=True):
+ args, kwargs = (address,), {'params': params, 'headers': headers or {}}
+ return self._make_request(requests.get, args, kwargs, auth)
+
+ def post(self, address, data=None, headers=None, auth=True):
+ args, kwargs = (address,), {'data': data, 'headers': headers or {}}
+ return self._make_request(requests.post, args, kwargs, auth)
+
+ def _make_request(self, method, args, kwargs, auth):
+ if auth:
+ kwargs['headers'].update(self._get_auth_headers())
+ response = method(*args, **kwargs)
+ content = self._parse_response(response)
+ if response.status_code == requests.codes.ok:
+ return content
+ else:
+ logger.error('[%s]: %s', response.status_code, response.text)
+ error = self.extract_error(content)
+ raise ValueError(error)
+
+ def _get_auth_headers(self):
+ if not self.access_token:
+ self.access_token = self.client.get_access_token(self.code)
+ return {'Authorization': 'Bearer %s' % (self.access_token,)}
+
+ def _parse_response(self, response):
+ if 'application/json' in response.headers['Content-Type']:
+ return response.json()
+ else:
+ content = urlparse.parse_qsl(response.text)
+ content = dict((x, y[0] if len(y) == 1 else y) for x, y in content)
+ return content
+
+
+class GoogleConnection(OAuth2Connection):
+
+ def extract_error(self, content):
+ return content['error']
+
+
+class FacebookConnection(OAuth2Connection):
+
+ def extract_error(self, content):
+ return content['error']['message']
+
+
+class OAuth2Client(object):
+
+ service = None
+ connection_class = None
+ client_id = None
+ client_secret = None
+ auth_uri = None
+ token_uri = None
+ user_info_uri = None
+ scope = None
+
+ def __init__(self, local_host, code=None):
+ self.local_host = local_host
+ if code:
+ self.connection = self.connection_class(code=code, client=self)
+
+ def get_redirect_uri(self):
+ kwargs = {'service': self.service}
+ path = reverse('registration:oauth_callback', kwargs=kwargs)
+ return urlparse.urljoin(self.local_host, path)
+
+ def get_login_uri(self):
+ data = {'response_type': 'code',
+ 'scope': self.scope,
+ 'redirect_uri': self.get_redirect_uri(),
+ 'client_id': self.client_id}
+ query = urllib.urlencode(data)
+ return urlparse.urljoin(self.auth_uri, url(query=query))
+
+ def get_user_info(self):
+ return self.connection.get(self.user_info_uri)
+
+ def get_access_token(self, code):
+ data = {'grant_type': 'authorization_code',
+ 'client_id': self.client_id,
+ 'client_secret': self.client_secret,
+ 'code': code,
+ 'redirect_uri': self.get_redirect_uri(),
+ 'scope': self.scope}
+ response = self.connection.post(self.token_uri, data=data, auth=False)
+ return response['access_token']
+
+
+class GoogleClient(OAuth2Client):
+
+ service = GOOGLE
+ connection_class = GoogleConnection
+
+ client_id = settings.GOOGLE_CLIENT_ID
+ client_secret = settings.GOOGLE_SECRET
+
+ auth_uri = 'https://accounts.google.com/o/oauth2/auth'
+ token_uri = 'https://accounts.google.com/o/oauth2/token'
+ user_info_uri = 'https://www.googleapis.com/oauth2/v1/userinfo'
+
+ scope = ' '.join(['https://www.googleapis.com/auth/userinfo.email',
+ 'https://www.googleapis.com/auth/plus.me'])
+
+ def get_user_info(self):
+ response = super(GoogleClient, self).get_user_info()
+ if response['verified_email']:
+ return response
+ else:
+ raise ValueError('Google account not verified.')
+
+
+class FacebookClient(OAuth2Client):
+
+ service = FACEBOOK
+ connection_class = FacebookConnection
+
+ client_id = settings.FACEBOOK_APP_ID
+ client_secret = settings.FACEBOOK_SECRET
+
+ auth_uri = 'https://www.facebook.com/dialog/oauth'
+ token_uri = 'https://graph.facebook.com/oauth/access_token'
+ user_info_uri = 'https://graph.facebook.com/me'
+
+ scope = ','.join(['email'])
+
+ def get_user_info(self):
+ response = super(FacebookClient, self).get_user_info()
+ if response['verified']:
+ return response
+ else:
+ raise ValueError('Facebook account not verified.')
diff --git a/registration/views.py b/registration/views.py
index 9e85cee6cf..fc3abc7cfd 100644
--- a/registration/views.py
+++ b/registration/views.py
@@ -1,30 +1,25 @@
from django.contrib.auth.views import (
login as django_login_view,
- logout as django_logout,
-)
+ logout as django_logout_view)
from django.contrib import messages
from django.contrib.auth import (
login as auth_login,
- authenticate,
- get_user_model,
-)
-from django.core.urlresolvers import reverse
-from django.core.mail.message import EmailMessage
-from django.http import HttpResponseNotFound, HttpResponseBadRequest
+ get_user_model)
from django.shortcuts import redirect
from django.template.response import TemplateResponse
from django.utils import timezone
-
-from .forms import LoginForm, EmailForm, EmailConfirmationFormset
-from .models import ExternalUserData, EmailConfirmation
+from django.utils.translation import ugettext_lazy as _
+
+from .forms import (
+ EmailConfirmationFormset,
+ RequestEmailConfirmationForm,
+ LoginForm,
+ OAuth2CallbackForm)
+from .models import EmailConfirmation
from .utils import (
- facebook_callback,
- google_callback,
- get_google_login_url,
get_facebook_login_url,
- get_email_confirmation_message,
- get_protocol_and_host,
-)
+ get_google_login_url,
+ get_protocol_and_host)
User = get_user_model()
now = timezone.now
@@ -39,86 +34,44 @@ def login(request):
def logout(request):
- return django_logout(request, template_name='registration/logout.html')
+ return django_logout_view(request, template_name='registration/logout.html')
def oauth_callback(request, service):
local_host = get_protocol_and_host(request)
-
- if service == 'facebook':
- email, external_username = facebook_callback(local_host, request.GET)
- elif service == 'google':
- email, external_username = google_callback(local_host, request.GET)
- else:
- return HttpResponseNotFound()
-
- if not external_username:
- messages.warning(
- request,
- 'Failed to retrieve user information from external service. '
- 'Please try again.')
- return redirect(reverse('registration:login'))
-
- user = authenticate(external_service=service,
- external_username=external_username)
-
- if user:
- _login_user(request, user)
- return redirect('home')
+ form = OAuth2CallbackForm(service=service, local_host=local_host,
+ data=request.GET)
+ if form.is_valid():
+ try:
+ user = form.get_authenticated_user()
+ _login_user(request, user)
+ return redirect('home')
+ except ValueError, e:
+ messages.warning(request, unicode(e))
else:
- request.session['confirmed_email'] = email
- request.session['external_service'] = service
- request.session['external_username'] = external_username
- return redirect('registration:register')
+ for field, errors in form.errors.items():
+ print form.errors
+ for error in errors:
+ messages.warning(request, '[%s] %s' % (field, error))
+ return redirect('registration:login')
-def register(request):
+def request_email_confirmation(request):
local_host = get_protocol_and_host(request)
-
- if request.method == 'GET':
- email = request.session.get('confirmed_email', None)
- form = EmailForm({'email': email} if email else None)
-
if request.method == 'POST':
- form = EmailForm(request.POST)
+ form = RequestEmailConfirmationForm(local_host=local_host,
+ data=request.POST)
if form.is_valid():
- submitted_email = form.cleaned_data['email']
- confirmed_email = request.session.pop('confirmed_email', '')
- try:
- external_user_data = {
- 'username': request.session.pop('external_username'),
- 'provider': request.session.pop('external_service')
- }
- except KeyError:
- external_user = None
- else:
- external_user, _ = ExternalUserData.objects.get_or_create(
- **external_user_data)
-
- if submitted_email == confirmed_email:
- if not external_user:
- # TODO: this should never happen unless sb is hacking
- return HttpResponseBadRequest()
- user, _ = User.objects.get_or_create(email=submitted_email)
- if external_user and not external_user.user:
- external_user.user = user
- external_user.save()
- user = authenticate(user=user)
- _login_user(request, user)
- else:
- email_confirmation = EmailConfirmation.objects.create(
- email=submitted_email, external_user=external_user)
- message = get_email_confirmation_message(
- local_host, email_confirmation)
- subject = '[Saleor] Email confirmation'
- EmailMessage(subject, message, to=[submitted_email]).send()
- messages.warning(
- request,
- 'We have sent you a confirmation email. '
+ form.send()
+ msg = _('Confirmation email has been sent. '
'Please check your inbox.')
+ messages.success(request, msg)
return redirect('home')
+ else:
+ form = RequestEmailConfirmationForm(local_host=local_host)
- return TemplateResponse(request, 'registration/register.html',
+ return TemplateResponse(request,
+ 'registration/request_email_confirmation.html',
{'form': form})
@@ -130,18 +83,16 @@ def confirm_email(request, pk, token):
except EmailConfirmation.DoesNotExist:
return TemplateResponse(request, 'registration/invalid_token.html')
- if request.method == 'GET':
- formset = EmailConfirmationFormset(
- email_confirmation=email_confirmation)
-
if request.method == 'POST':
formset = EmailConfirmationFormset(
email_confirmation=email_confirmation, data=request.POST)
if formset.is_valid():
- user = formset.save()
- user = authenticate(user=user)
+ user = formset.get_authenticated_user()
_login_user(request, user)
return redirect('home')
+ else:
+ formset = EmailConfirmationFormset(
+ email_confirmation=email_confirmation)
return TemplateResponse(
request, 'registration/set_password.html', {'formset': formset})
@@ -149,5 +100,5 @@ def confirm_email(request, pk, token):
def _login_user(request, user):
auth_login(request, user)
- msg = 'You have been successfully logged in.'
+ msg = _('You have been successfully logged in.')
messages.success(request, msg)
diff --git a/setup.py b/setup.py
index c725c532b1..4da360fb80 100755
--- a/setup.py
+++ b/setup.py
@@ -33,10 +33,8 @@ setup(
'satchless>=1.0a0,<1.1a0',
'South>=0.7.6',
'unidecode',
- 'oauth2client>=1.1',
- 'httplib2>=0.8',
'purl>=0.4.1',
- 'facebook-sdk>=0.4.0'],
+ 'requests>=1.2.0'],
extras_require={
'lint': ['pylint==0.26.0', 'django-lint==dev']},
dependency_links=[