Skip to content

armgit / wger

Public Imported from GitHub
0

Self hosted FLOSS fitness/workout, nutrition and weight tracker

Move the email changing logic to allauth

Roland Geideraf1aeee204fb
diff --git a/settings/settings_global.py b/settings/settings_global.py
index cce3c8e06..d8102825a 100644
--- a/settings/settings_global.py
+++ b/settings/settings_global.py
@@ -224,6 +224,11 @@ ACCOUNT_CONFIRM_EMAIL_ON_GET = True
ACCOUNT_EMAIL_CONFIRMATION_EXPIRE_DAYS = 2
ACCOUNT_ADAPTER = 'wger.core.account_adapter.WgerAccountAdapter'
+# Treat a user as having a single email address: changing it adds a pending
+# address that only replaces the current one (and updates User.email) once
+# confirmed via the verification link.
+ACCOUNT_CHANGE_EMAIL = True
+
#
# Login
#
diff --git a/wger/core/forms.py b/wger/core/forms.py
index f5237f13b..9e17b1e67 100644
--- a/wger/core/forms.py
+++ b/wger/core/forms.py
@@ -128,11 +128,6 @@ class UserLoginForm(AuthenticationForm):
class UserPreferencesForm(forms.ModelForm):
first_name = forms.CharField(label=gettext_lazy('First name'), required=False)
last_name = forms.CharField(label=gettext_lazy('Last name'), required=False)
- email = EmailField(
- label=gettext_lazy('Email'),
- help_text=gettext_lazy('Used for password resets and, optionally, e-mail reminders.'),
- required=False,
- )
birthdate = forms.DateField(
label=gettext_lazy('Date of Birth'),
required=False,
@@ -178,7 +173,6 @@ class UserPreferencesForm(forms.ModelForm):
self.helper.layout = Layout(
Fieldset(
_('Personal data'),
- 'email',
Row(
Column('first_name', css_class='col-6'),
Column('last_name', css_class='col-6'),
@@ -207,6 +201,15 @@ class UserPreferencesForm(forms.ModelForm):
ButtonHolder(Submit('submit', _('Save'), css_class='btn-success btn-block')),
)
+ def save(self, commit=True):
+ """Also persist the first/last name onto the related User."""
+ profile = super().save(commit=commit)
+ if commit:
+ self.user.first_name = self.cleaned_data['first_name']
+ self.user.last_name = self.cleaned_data['last_name']
+ self.user.save(update_fields=['first_name', 'last_name'])
+ return profile
+
class UserEmailForm(forms.ModelForm):
email = EmailField(
diff --git a/wger/core/templates/account/email_change.html b/wger/core/templates/account/email_change.html
new file mode 100644
index 000000000..c70ca3cde
--- /dev/null
+++ b/wger/core/templates/account/email_change.html
@@ -0,0 +1,69 @@
+{% extends "base.html" %}
+{% load i18n wger_extras %}
+
+{% block title %}{% translate "Email address" %}{% endblock %}
+
+
+{% block content %}
+ <p>
+ {% blocktranslate trimmed %}
+ Your email address is used for password resets and, optionally, workout
+ reminders. A new address only becomes active once you confirm it via the
+ link sent to it.
+ {% endblocktranslate %}
+ </p>
+
+ {% if current_emailaddress %}
+ <div class="card mb-3 text-white bg-success">
+ <div class="card-body">
+ <span class="{% fa_class 'envelope-circle-check' %}"></span>
+ {% translate "Current email" %}: <strong>{{ current_emailaddress.email }}</strong>
+ </div>
+ </div>
+ {% endif %}
+
+ {% if new_emailaddress %}
+ <div class="card mb-3 bg-light">
+ <div class="card-body">
+ <p>
+ <span class="{% fa_class 'envelope' %}"></span>
+ {% blocktranslate with email=new_emailaddress.email trimmed %}
+ Pending confirmation: <strong>{{ email }}</strong>
+ {% endblocktranslate %}
+ </p>
+ <form method="post" action="{% url 'account_email' %}" class="d-inline">
+ {% csrf_token %}
+ <input type="hidden" name="email" value="{{ new_emailaddress.email }}">
+ <button type="submit" name="action_send" class="btn btn-sm btn-light">
+ {% translate "Resend confirmation email" %}
+ </button>
+ {% if current_emailaddress %}
+ <button type="submit" name="action_remove" class="btn btn-sm btn-light">
+ {% translate "Cancel change" %}
+ </button>
+ {% endif %}
+ </form>
+ </div>
+ </div>
+ {% endif %}
+
+ <form method="post" action="{% url 'account_email' %}" class="wger-form" novalidate>
+ {% csrf_token %}
+ <div class="mb-3">
+ <label for="{{ form.email.id_for_label }}" class="form-label">
+ {% translate "Change to" %}
+ </label>
+ <input type="email"
+ name="email"
+ id="{{ form.email.id_for_label }}"
+ value="{{ form.email.value|default:'' }}"
+ class="form-control {% if form.email.errors %}is-invalid{% endif %}">
+ {% for error in form.email.errors %}
+ <div class="invalid-feedback">{{ error }}</div>
+ {% endfor %}
+ </div>
+ <button type="submit" name="action_add" class="btn btn-success btn-block">
+ {% translate "Change email" %}
+ </button>
+ </form>
+{% endblock %}
diff --git a/wger/core/templates/user/preferences.html b/wger/core/templates/user/preferences.html
index 64c936e4b..47ab6d095 100644
--- a/wger/core/templates/user/preferences.html
+++ b/wger/core/templates/user/preferences.html
@@ -22,10 +22,11 @@
<p>
<span class="{% fa_class 'envelope' %}"></span>
{% translate "Unverified email" %}
- <br>
- <a href="{% url 'core:user:confirm-email' %}">{% translate "Send verification email" %}</a>
</p>
{% endif %}
+ <p>
+ <a href="{% url 'account_email' %}">{% translate "Manage email address" %}</a>
+ </p>
<p>
<small class="text-muted">
{% translate "You need to verify your email to contribute exercises" %}
@@ -50,6 +51,10 @@
{% translate "Options" %}
</button>
<div class="dropdown-menu">
+ <a href="{% url 'account_email' %}" class="dropdown-item">
+ <span class="{% fa_class 'envelope' %}"></span>
+ {% translate "Email address" %}
+ </a>
<a href="{% url 'core:user:change-password' %}" class="dropdown-item">
<span class="{% fa_class 'key' %}"></span>
{% translate "Change password" %}
diff --git a/wger/core/tests/test_preferences.py b/wger/core/tests/test_preferences.py
index 3772def9f..cc6c41619 100644
--- a/wger/core/tests/test_preferences.py
+++ b/wger/core/tests/test_preferences.py
@@ -41,7 +41,6 @@ class PreferencesTestCase(WgerTestCase):
self.form_data = {
'show_comments': True,
'show_english_ingredients': True,
- 'email': '',
'first_name': '',
'last_name': '',
'workout_reminder_active': True,
@@ -56,7 +55,8 @@ class PreferencesTestCase(WgerTestCase):
def test_preferences(self):
"""
- Helper function to test the preferences page
+ Submitting the preferences form persists the UserProfile settings as
+ well as the first/last name on the related User.
"""
self.user_login('test')
@@ -71,17 +71,19 @@ class PreferencesTestCase(WgerTestCase):
# Change some preferences
response = self.client.post(
reverse('core:user:preferences'),
- {**self.form_data, 'email': '[email protected]'},
+ {**self.form_data, 'first_name': 'Test', 'last_name': 'User'},
)
self.assertEqual(response.status_code, 302)
response = self.client.get(reverse('core:user:preferences'))
- profile = User.objects.get(username='test').userprofile
+ user = User.objects.get(username='test')
+ profile = user.userprofile
self.assertTrue(profile.show_english_ingredients)
self.assertTrue(profile.workout_reminder_active)
self.assertEqual(profile.workout_reminder, 30)
self.assertEqual(profile.workout_duration, 12)
- self.assertEqual(User.objects.get(username='test').email, '[email protected]')
+ self.assertEqual(user.first_name, 'Test')
+ self.assertEqual(user.last_name, 'User')
# Change some preferences
response = self.client.post(
@@ -101,7 +103,23 @@ class PreferencesTestCase(WgerTestCase):
profile = response.context['user'].userprofile
self.assertFalse(profile.show_comments)
self.assertTrue(profile.show_english_ingredients)
- self.assertEqual(response.context['user'].email, '')
+
+ def test_email_is_not_editable_from_preferences(self):
+ """
+ Email management was moved to allauth's EmailView: the preferences
+ page no longer renders an email field and links to it instead.
+ """
+ self.user_login('test')
+ response = self.client.get(reverse('core:user:preferences'))
+ self.assertNotContains(response, 'name="email"')
+ self.assertContains(response, reverse('account_email'))
+
+ def test_account_email_page_renders(self):
+ """The allauth email page uses wger's template and is reachable."""
+ self.user_login('test')
+ response = self.client.get(reverse('account_email'))
+ self.assertEqual(response.status_code, 200)
+ self.assertTemplateUsed(response, 'account/email_change.html')
def test_address(self):
"""
@@ -132,64 +150,15 @@ class PreferencesTestCase(WgerTestCase):
},
)
- def test_duplicate_email_shows_error_and_saves_nothing(self):
- """
- Submitting the preferences form with an email that already belongs to
- another account must show an inline field error AND a top-of-page
- banner, and must not persist any of the submitted fields.
-
- Regression test for the silent-failure / half-save behavior in the
- preferences view: previously the duplicate-email error lived on a
- second form that wasn't put in the context, so the page reloaded
- silently while UserProfile fields had already been saved.
- """
- self.user_login('test')
-
- user_before = User.objects.get(username='test')
- snapshot = {
- 'email': user_before.email,
- 'first_name': user_before.first_name,
- 'last_name': user_before.last_name,
- 'height': user_before.userprofile.height,
- 'birthdate': user_before.userprofile.birthdate,
- }
-
- response = self.client.post(
- reverse('core:user:preferences'),
- {
- **self.form_data,
- 'email': '[email protected]',
- 'first_name': 'Brand',
- 'last_name': 'New',
- 'birthdate': '01/01/2000',
- 'height': 175,
- },
- )
-
- self.assertEqual(response.status_code, 200)
- self.assertContains(response, 'This e-mail address is already in use.')
- self.assertContains(response, 'is-invalid')
- self.assertContains(response, 'invalid-feedback')
- self.assertContains(response, 'alert-danger')
- self.assertContains(response, 'Please correct the errors below.')
-
- user_after = User.objects.get(username='test')
- self.assertEqual(user_after.email, snapshot['email'])
- self.assertEqual(user_after.first_name, snapshot['first_name'])
- self.assertEqual(user_after.last_name, snapshot['last_name'])
- self.assertEqual(user_after.userprofile.height, snapshot['height'])
- self.assertEqual(user_after.userprofile.birthdate, snapshot['birthdate'])
-
- def test_invalid_email_format_shows_error_and_saves_nothing(self):
+ def test_invalid_field_shows_error_and_saves_nothing(self):
"""
- Submitting the preferences form with a malformed email must show an inline
- field error AND a banner, and not persist any submitted fields
+ A validation error on the preferences form shows a banner and persists
+ nothing — neither the UserProfile fields nor the first/last name.
"""
self.user_login('test')
user_before = User.objects.get(username='test')
snapshot = {
- 'email': user_before.email,
'first_name': user_before.first_name,
'last_name': user_before.last_name,
'height': user_before.userprofile.height,
@@ -200,23 +169,18 @@ class PreferencesTestCase(WgerTestCase):
reverse('core:user:preferences'),
{
**self.form_data,
- 'email': 'not an email',
'first_name': 'Brand',
'last_name': 'New',
'birthdate': '01/01/2000',
- 'height': 175,
+ 'height': '', # required field left blank
},
)
self.assertEqual(response.status_code, 200)
- self.assertContains(response, 'Enter a valid email address.')
- self.assertContains(response, 'is-invalid')
- self.assertContains(response, 'invalid-feedback')
self.assertContains(response, 'alert-danger')
self.assertContains(response, 'Please correct the errors below.')
user_after = User.objects.get(username='test')
- self.assertEqual(user_after.email, snapshot['email'])
self.assertEqual(user_after.first_name, snapshot['first_name'])
self.assertEqual(user_after.last_name, snapshot['last_name'])
self.assertEqual(user_after.userprofile.height, snapshot['height'])
diff --git a/wger/core/tests/test_verification.py b/wger/core/tests/test_verification.py
index 951cd4e05..1d7c13c0d 100644
--- a/wger/core/tests/test_verification.py
+++ b/wger/core/tests/test_verification.py
@@ -37,87 +37,6 @@ from wger.core.tests.base_testcase import WgerTestCase
logger = logging.getLogger(__name__)
-@override_settings(EMAIL_BACKEND='django.core.mail.backends.locmem.EmailBackend')
-class EmailVerificationFromPreferencesTestCase(WgerTestCase):
- """
- Tests that clicking the verification link in the preferences sidebar
- sends a verification email via allauth.
- """
-
- def test_confirm_email_sends_mail_for_unverified_user(self):
- """
- An unverified user clicking confirm-email receives a verification email
- """
-
- # User 1 (admin) has verified=False in the fixtures
- self.user_login('admin')
-
- mail.outbox = []
- response = self.client.get(reverse('core:user:confirm-email'))
-
- # Redirects to dashboard
- self.assertEqual(response.status_code, 302)
- self.assertIn(reverse('core:dashboard'), response.url)
-
- # A verification email was sent
- self.assertEqual(len(mail.outbox), 1)
- self.assertIn('[email protected]', mail.outbox[0].to)
-
- def test_confirm_email_link_verifies_email(self):
- """
- Following the confirmation link from the email marks the address as verified
- """
-
- # User 1 (admin) has verified=False in the fixtures
- self.user_login('admin')
-
- mail.outbox = []
- self.client.get(reverse('core:user:confirm-email'))
- self.assertEqual(len(mail.outbox), 1)
-
- # Extract the confirmation key from the email body
- email_body = mail.outbox[0].body
- match = re.search(r'/account/confirm-email/([^/\s]+)/', email_body)
- self.assertIsNotNone(match, 'Could not find confirmation link in email body')
- key = match.group(1)
-
- # Visit the confirmation URL (GET shows the page, POST confirms)
- confirm_url = reverse('account_confirm_email', args=[key])
- self.client.get(confirm_url)
-
- # The email should now be verified
- user = User.objects.get(username='admin')
- email_obj = EmailAddress.objects.get_for_user(user, user.email)
- self.assertTrue(email_obj.verified)
-
- def test_confirm_email_no_mail_for_verified_user(self):
- """
- A verified user clicking confirm-email does not receive a new email
- """
-
- # User 4 (trainer1) has verified=True in the fixtures
- self.user_login('trainer1')
-
- mail.outbox = []
- response = self.client.get(reverse('core:user:confirm-email'))
-
- # Redirects to dashboard
- self.assertEqual(response.status_code, 302)
-
- # No email was sent
- self.assertEqual(len(mail.outbox), 0)
-
- def test_confirm_email_requires_login(self):
- """
- Anonymous users are redirected to the login page
- """
-
- self.user_logout()
- response = self.client.get(reverse('core:user:confirm-email'))
- self.assertEqual(response.status_code, 302)
- self.assertIn('/login', response.url)
-
-
@override_settings(EMAIL_BACKEND='django.core.mail.backends.locmem.EmailBackend')
class EmailVerificationFromAPITestCase(WgerTestCase):
"""
@@ -215,7 +134,6 @@ class UserProfileEmailUpdateTestCase(WgerTestCase):
Claiming another user's email must fail with 400.
"""
self.user_login('test')
- admin_email = User.objects.get(username='admin').email or '[email protected]'
# Make sure admin has a known email so the collision is meaningful
admin = User.objects.get(username='admin')
admin.email = '[email protected]'
diff --git a/wger/core/urls.py b/wger/core/urls.py
index df0ca1813..eaf447578 100644
--- a/wger/core/urls.py
+++ b/wger/core/urls.py
@@ -79,7 +79,6 @@ patterns_user = [
path('logout', user.logout, name='logout'),
path('delete', user.delete, name='delete'),
path('<int:user_pk>/delete', user.delete, name='delete'),
- path('confirm-email', user.confirm_email, name='confirm-email'),
path('<int:user_pk>/trainer-login', user.trainer_login, name='trainer-login'),
path('registration', user.registration, name='registration'),
path('preferences', user.preferences, name='preferences'),
diff --git a/wger/core/views/user.py b/wger/core/views/user.py
index 74f0c873f..a405bc725 100644
--- a/wger/core/views/user.py
+++ b/wger/core/views/user.py
@@ -332,59 +332,25 @@ def preferences(request):
context = {}
context.update(csrf(request))
- email_verified = request.user.userprofile.is_verified
-
if request.method == 'POST':
form = UserPreferencesForm(data=request.POST, instance=request.user.userprofile)
form.user = request.user
- email_form = UserPersonalInformationForm(data=request.POST, instance=request.user)
-
- # Validate both forms before saving anything, so a single bad field
- # (e.g. a duplicate email) never half-persists the submission.
- prefs_valid = form.is_valid()
- email_valid = email_form.is_valid()
-
- if prefs_valid and email_valid:
- # If the user changes the email, it is no longer verified
- if request.user.email != email_form.cleaned_data.get('email'):
- logger.debug('adding email with verified flag and also, sends email confirmation')
- EmailAddress.objects.add_email(
- request,
- request.user,
- email_form.cleaned_data['email'],
- confirm=True,
- )
- email_form.save()
+ if form.is_valid():
form.save()
-
messages.success(request, _('Settings successfully updated'))
return HttpResponseRedirect(reverse('core:user:preferences'))
- # The template only renders `form`, so copy any errors from
- # `email_form` onto the rendered form so they show up inline next
- # to the offending field. Skip duplicates that already exist on
- # `form` (the email field's format validator runs on both forms).
- for field, errors in email_form.errors.items():
- target = field if field in form.fields else None
- existing = set(form.errors.get(target or '__all__', []))
- for err in errors:
- if err in existing:
- continue
- form.add_error(target, err)
- existing.add(err)
-
messages.error(request, _('Please correct the errors below.'))
else:
data = {
'first_name': request.user.first_name,
'last_name': request.user.last_name,
- 'email': request.user.email,
}
form = UserPreferencesForm(initial=data, instance=request.user.userprofile)
context['form'] = form
- context['email_verified'] = email_verified
+ context['email_verified'] = request.user.userprofile.is_verified
return render(request, 'user/preferences.html', context)
@@ -740,18 +706,6 @@ class WgerPasswordResetConfirmView(PasswordResetConfirmView):
return form
-@login_required
-def confirm_email(request):
- email_obj = EmailAddress.objects.get_for_user(request.user, request.user.email)
- if not email_obj.verified:
- email_obj.send_confirmation(request)
- messages.success(
- request, _('A verification email was sent to %(email)s') % {'email': request.user.email}
- )
-
- return HttpResponseRedirect(reverse('core:dashboard'))
-
-
class WgerLoginView(LoginView):
"""
If the user is already logged in and there's a "next" parameter in the URL,