Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Handle email change when sb else is logged in
Marek Brzóska05b2b1edb7bf
diff --git a/registration/forms.py b/registration/forms.pyindex 7bfd7ce6ba..8840e0bdd9 100644--- a/registration/forms.py+++ b/registration/forms.py@@ -18,6 +18,13 @@ class LoginForm(AuthenticationForm):username = forms.EmailField(label=ugettext_lazy("Email"), max_length=75)+ def __init__(self, request=None, *args, **kwargs):+ super(LoginForm, self).__init__(request=request, *args, **kwargs)+ if request:+ email = request.GET.get('email')+ if email:+ self.fields['username'].initial = email+class RequestEmailConfirmationForm(forms.Form):diff --git a/registration/tests.py b/registration/tests.pyindex 90643a9258..d3e5e7e63e 100644--- a/registration/tests.py+++ b/registration/tests.py@@ -14,7 +14,7 @@ from .utils import (OAuth2RequestAuthorizer,OAuth2Client,parse_response)-from .views import oauth_callback+from .views import oauth_callback, change_emailUser = get_user_model()@@ -27,7 +27,7 @@ class LoginUrlsTestCase(TestCase):def test_facebook_login_url(self):"""Facebook login url is properly generated"""- facebook_client = FacebookClient(base_url='localhost')+ facebook_client = FacebookClient(local_host='localhost')facebook_login_url = URL(facebook_client.get_login_uri())query = facebook_login_url.query_params()callback_url = URL(query['redirect_uri'][0])@@ -39,7 +39,7 @@ class LoginUrlsTestCase(TestCase):def test_google_login_url(self):"""Google login url is properly generated"""- google_client = GoogleClient(base_url='local_host')+ google_client = GoogleClient(local_host='local_host')google_login_url = URL(google_client.get_login_uri())params = google_login_url.query_params()callback_url = URL(params['redirect_uri'][0])@@ -117,12 +117,12 @@ class AccessTokenTestCase(BaseCommunicationTestCase):def test_token_is_obtained_on_construction(self):"""OAuth2 client asks for access token if temporary code is available"""self.access_token_response.status_code = sentinel.ok- TestClient(base_url='http://localhost', code=sentinel.code)+ TestClient(local_host='http://localhost', code=sentinel.code)self.requests_mock.post.assert_called_once()def test_token_success(self):"""OAuth2 client properly obtains access token"""- client = TestClient(base_url='http://localhost')+ client = TestClient(local_host='http://localhost')self.access_token_response.status_code = sentinel.okaccess_token = client.get_access_token(code=sentinel.code)self.assertEquals(access_token, sentinel.access_token)@@ -138,7 +138,7 @@ class AccessTokenTestCase(BaseCommunicationTestCase):def test_token_failure(self):"""OAuth2 client properly reacts to access token fetch failure"""- client = TestClient(base_url='http://localhost')+ client = TestClient(local_host='http://localhost')self.access_token_response.status_code = sentinel.failself.assertRaises(ValueError, client.get_access_token,code=sentinel.code)@@ -155,7 +155,7 @@ class UserInfoTestCase(BaseCommunicationTestCase):def test_user_info_success(self):"""OAuth2 client properly fetches user info"""- client = TestClient(base_url='http://localhost')+ client = TestClient(local_host='http://localhost')self.parse_mock.return_value = sentinel.user_infoself.user_info_response.status_code = sentinel.okuser_info = client.get_user_info()@@ -163,21 +163,21 @@ class UserInfoTestCase(BaseCommunicationTestCase):def test_user_data_failure(self):"""OAuth2 client reacts well to user info fetch failure"""- client = TestClient(base_url='http://localhost')+ client = TestClient(local_host='http://localhost')self.assertRaises(ValueError, client.get_user_info)def test_google_user_data_email_not_verified(self):"""Google OAuth2 client checks for email verification"""self.user_info_response.status_code = sentinel.okself.parse_mock.return_value = {'verified_email': False}- google_client = GoogleClient(base_url='http://localhost')+ google_client = GoogleClient(local_host='http://localhost')self.assertRaises(ValueError, google_client.get_user_info)def test_facebook_user_data_account_not_verified(self):"""Facebook OAuth2 client checks for account verification"""self.user_info_response.status_code = sentinel.okself.parse_mock.return_value = {'verified': False}- facebook_client = FacebookClient(base_url='http://localhost')+ facebook_client = FacebookClient(local_host='http://localhost')self.assertRaises(ValueError, facebook_client.get_user_info)@@ -272,3 +272,58 @@ class EmailConfirmationTestCase(TestCase):self.assertEquals(authed_user, sentinel.authed_user)user.set_unusable_password.assert_called_once()authenticate_mock.assert_called_once_with(user=user)+++class EmailChangeTestCase(TestCase):++ @patch('registration.views.now')+ @patch('registration.views.EmailChangeRequest.objects.get')+ def test_another_user_logged_out(self, get, now):++ # user requests email change+ user = Mock()+ token_object = Mock()+ token_object.token = 'sometokencontent'+ token_object.user = user+ get.return_value = token_object++ # another user is logged in+ another_user = Mock()+ request = Mock()+ request.user = another_user++ # first user clicks link in his email+ result = change_email(request, token_object.token)+ self.assertEquals(result.status_code, 302)+ get.assert_called_once_with(+ token=token_object.token, valid_until__gte=now())+ self.assertFalse(request.user.is_authenticated())+ self.assertEqual(token_object.delete.call_count, 0)++ @patch('registration.views.now')+ @patch('registration.views.EmailChangeRequest.objects.get')+ def test_user_logged_in(self, get, now):++ # user requests email change+ user = Mock()+ token_object = Mock()+ token_object.token = 'sometokencontent'+ token_object.user = user+ get.return_value = token_object++ # user is logged in+ request = Mock()+ request.user = user++ # user clicks link in his email+ result = change_email(request, token_object.token)+ self.assertEquals(result.status_code, 302)+ get.assert_called_once_with(+ token=token_object.token, valid_until__gte=now())+ # user stays logged in+ self.assertTrue(request.user.is_authenticated())+ # token is deleted+ token_object.delete.assert_called_once_with()+ user.save.assert_called_once_with()+ # user email gets changed+ self.assertEqual(user.email, token_object.email)diff --git a/registration/views.py b/registration/views.pyindex ca1c948ec1..152336669b 100644--- a/registration/views.py+++ b/registration/views.py@@ -1,6 +1,7 @@+from urllib import urlencode+from django.conf import settingsfrom django.contrib.auth.views import login as django_login_view-from django.contrib.auth.decorators import login_requiredfrom django.contrib import messagesfrom django.contrib.auth import (login as auth_login,@@ -21,7 +22,8 @@ from .models import EmailConfirmationRequest, EmailChangeRequestfrom .utils import (get_facebook_login_url,get_google_login_url,- get_local_host)+ get_local_host,+ url)User = get_user_model()now = timezone.now@@ -118,15 +120,25 @@ def confirm_email(request, token):request, 'registration/set_password.html', {'form': form})-@login_requireddef change_email(request, token):try:email_confirmation_request = EmailChangeRequest.objects.get(- token=token, valid_until__gte=now(), user=request.user)- # TODO: cronjob (celery task) to delete stale tokens+ token=token, valid_until__gte=now())+ # TODO: cronjob (celery task) to delete stale tokensexcept EmailChangeRequest.DoesNotExist:return TemplateResponse(request, 'registration/invalid_token.html')+ # if another user is logged in, we need to log him out, to allow the email+ # owner confirm his identity+ if request.user != email_confirmation_request.user:+ auth_logout(request)+ if not request.user.is_authenticated():+ query = urlencode({+ 'next': request.get_full_path(),+ 'email': email_confirmation_request.user.email})+ login_url = url(path=settings.LOGIN_URL, query=query)+ return redirect(login_url)+request.user.email = email_confirmation_request.emailrequest.user.save()email_confirmation_request.delete()diff --git a/saleor/settings.py b/saleor/settings.pyindex 120350cb5c..c2daa7b094 100644--- a/saleor/settings.py+++ b/saleor/settings.py@@ -164,6 +164,8 @@ CANONICAL_HOSTNAME = 'localhost:8000'EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'+LOGIN_URL = '/account/login'+WARN_ABOUT_INVALID_HTML5_OUTPUT = FalseSATCHLESS_DEFAULT_CURRENCY = 'USD'