Skip to content

armgit / wger

Public Imported from GitHub
0

Self hosted FLOSS fitness/workout, nutrition and weight tracker

Move the web password reset to allauth

Roland Geiderc311400d57ec
diff --git a/settings/settings_global.py b/settings/settings_global.py
index af29e2b3e..b523f9c9b 100644
--- a/settings/settings_global.py
+++ b/settings/settings_global.py
@@ -276,11 +276,13 @@ ACCOUNT_CHANGE_EMAIL = True
# authentication backend resolves the email against its EmailAddress table.
ACCOUNT_LOGIN_METHODS = {'username', 'email'}
-# Use wger's own login/signup forms (allauth's forms + the password-visibility
-# toggle, and a conditional reCAPTCHA field on signup).
+# Use wger's own login/signup/password reset forms (allauth's forms + the
+# password-visibility toggle, and a conditional reCAPTCHA field on signup and
+# password reset).
ACCOUNT_FORMS = {
'login': 'wger.core.forms.WgerLoginForm',
'signup': 'wger.core.forms.WgerSignupForm',
+ 'reset_password': 'wger.core.forms.WgerResetPasswordForm',
}
# django-axes handles login brute-force protection at the backend level (it
diff --git a/wger/core/forms.py b/wger/core/forms.py
index da7117f35..8eff4656a 100644
--- a/wger/core/forms.py
+++ b/wger/core/forms.py
@@ -21,7 +21,6 @@ from datetime import date
# Django
from django import forms
from django.conf import settings
-from django.contrib.auth.forms import PasswordResetForm
from django.contrib.auth.models import User
from django.core.exceptions import ValidationError
from django.forms import (
@@ -39,6 +38,7 @@ from django.utils.translation import (
# Third Party
from allauth.account.forms import (
LoginForm as AllauthLoginForm,
+ ResetPasswordForm as AllauthResetPasswordForm,
SignupForm as AllauthSignupForm,
)
from allauth.account.utils import filter_users_by_email
@@ -345,20 +345,29 @@ class UsernameConfirmationForm(Form):
return username
-class PasswordResetFormCaptcha(PasswordResetForm):
- captcha = ReCaptchaField(
- widget=ReCaptchaV3(action='password_reset'),
- label='reCaptcha',
- help_text=gettext_lazy('The form is secured with reCAPTCHA'),
- )
+class WgerResetPasswordForm(AllauthResetPasswordForm):
+ """
+ allauth's password reset form with an optional reCAPTCHA field (shown when
+ WGER_SETTINGS['USE_RECAPTCHA'] is set).
+ """
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
+ layout_fields = ['email']
+ if settings.WGER_SETTINGS['USE_RECAPTCHA']:
+ self.fields['captcha'] = ReCaptchaField(
+ widget=ReCaptchaV3(action='password_reset'),
+ label='reCaptcha',
+ help_text=gettext_lazy('The form is secured with reCAPTCHA'),
+ )
+ layout_fields.append('captcha')
+
self.helper = FormHelper()
+ self.helper.form_tag = False
self.helper.form_class = 'wger-form'
self.helper.layout = Layout(
- 'email',
- 'captcha',
+ *layout_fields,
+ # Not named "submit", see WgerSignupForm
ButtonHolder(Submit('submitBtn', _('Submit'), css_class='btn-success btn-block')),
)
diff --git a/wger/core/templates/account/login.html b/wger/core/templates/account/login.html
index 41e6fb455..19414b199 100644
--- a/wger/core/templates/account/login.html
+++ b/wger/core/templates/account/login.html
@@ -72,7 +72,7 @@
{% else %}
<span></span>
{% endif %}
- <a href="{% url 'core:user:password_reset' %}">
+ <a href="{% url 'account_reset_password' %}">
{% translate "Forgot password?" %}
</a>
</div>
diff --git a/wger/core/templates/account/password_reset.html b/wger/core/templates/account/password_reset.html
new file mode 100644
index 000000000..8bd39afba
--- /dev/null
+++ b/wger/core/templates/account/password_reset.html
@@ -0,0 +1,17 @@
+{% extends "base.html" %}
+{% load i18n crispy_forms_tags %}
+
+{% block title %}{% translate "Password Reset" %}{% endblock %}
+
+
+{% block content %}
+ <p>
+ {% translate "Forgotten your password? Enter your email address below, and we'll send you an email allowing you to reset it." %}
+ </p>
+
+ <form method="post" action="{% url 'account_reset_password' %}" data-disable-on-submit>
+ {% csrf_token %}
+ {{ redirect_field }}
+ {% crispy form %}
+ </form>
+{% endblock %}
diff --git a/wger/core/templates/account/password_reset_from_key.html b/wger/core/templates/account/password_reset_from_key.html
new file mode 100644
index 000000000..6a91b3db7
--- /dev/null
+++ b/wger/core/templates/account/password_reset_from_key.html
@@ -0,0 +1,23 @@
+{% extends "base.html" %}
+{% load i18n crispy_forms_tags %}
+
+{% block title %}{% if token_fail %}{% translate "Bad Token" %}{% else %}{% translate "Change Password" %}{% endif %}{% endblock %}
+
+
+{% block content %}
+ {% if token_fail %}
+ {% url 'account_reset_password' as passwd_reset_url %}
+ <p>
+ {% blocktranslate %}The password reset link was invalid, possibly because it has already been used. Please request a <a href="{{ passwd_reset_url }}">new password reset</a>.{% endblocktranslate %}
+ </p>
+ {% else %}
+ <form method="post" action="{{ action_url }}" class="wger-form" novalidate>
+ {% csrf_token %}
+ {{ redirect_field }}
+ {{ form|crispy }}
+ <button type="submit" name="action" class="btn btn-success btn-block">
+ {% translate "Change Password" %}
+ </button>
+ </form>
+ {% endif %}
+{% endblock %}
diff --git a/wger/core/templates/account/password_reset_from_key_done.html b/wger/core/templates/account/password_reset_from_key_done.html
new file mode 100644
index 000000000..b0d7b6ad5
--- /dev/null
+++ b/wger/core/templates/account/password_reset_from_key_done.html
@@ -0,0 +1,11 @@
+{% extends "base.html" %}
+{% load i18n %}
+
+{% block title %}{% translate "Password reset complete" %}{% endblock %}
+
+
+{% block content %}
+ <p>{% translate "Your password has been set. You may go ahead and log in now." %}</p>
+
+ <p><a href="{% url 'core:user:login' %}">{% translate "Log in" %}</a></p>
+{% endblock %}
diff --git a/wger/core/templates/navigation.html b/wger/core/templates/navigation.html
index 0c0fd30f2..73ccf9ebc 100644
--- a/wger/core/templates/navigation.html
+++ b/wger/core/templates/navigation.html
@@ -285,7 +285,7 @@
{% endif %}
<li>
<a class="dropdown-item"
- href="{% url 'core:user:password_reset' %}">
+ href="{% url 'account_reset_password' %}">
{% translate "Reset password" %}
</a>
</li>
diff --git a/wger/core/templates/registration/password_reset_complete.html b/wger/core/templates/registration/password_reset_complete.html
deleted file mode 100644
index 44cfbd312..000000000
--- a/wger/core/templates/registration/password_reset_complete.html
+++ /dev/null
@@ -1,12 +0,0 @@
-{% extends "base.html" %}
-{% load i18n %}
-
-{% block title %}{% translate "Password reset complete" %}{% endblock %}
-
-
-{% block content %}
-<p>{% translate "Your password has been set. You may go ahead and log in now." %}</p>
-
-<p><a href="{% url 'core:user:login' %}">{% translate 'Log in' %}</a></p>
-
-{% endblock %}
diff --git a/wger/core/templates/registration/password_reset_done.html b/wger/core/templates/registration/password_reset_done.html
deleted file mode 100644
index 5c1767685..000000000
--- a/wger/core/templates/registration/password_reset_done.html
+++ /dev/null
@@ -1,10 +0,0 @@
-{% extends "base.html" %}
-{% load i18n %}
-
-{% block title %}{% translate "Password reset successful" %}{% endblock %}
-
-
-{% block content %}
-<p>{% translate "We've e-mailed you instructions for setting your password to the e-mail address you submitted. You should be receiving it shortly." %}</p>
-
-{% endblock %}
diff --git a/wger/core/templates/registration/password_reset_email.html b/wger/core/templates/registration/password_reset_email.html
deleted file mode 100644
index 4a90d7995..000000000
--- a/wger/core/templates/registration/password_reset_email.html
+++ /dev/null
@@ -1,15 +0,0 @@
-{% load i18n %}{% autoescape off %}
-{% blocktranslate %}You're receiving this e-mail because you requested a password reset for your user account at {{ site_name }}.{% endblocktranslate %}
-
-{% translate "Please go to the following page and choose a new password:" %}
-{% block reset_link %}
-{{ protocol }}://{{ domain }}{% url 'core:user:password_reset_confirm' uidb64=uid token=token %}
-{% endblock %}
-
-{% translate "Your username, in case you've forgotten:" %} {{ user.username }}
-
-{% translate "Thanks for using our site!" %}
-
-{% blocktranslate %}The {{ site_name }} team{% endblocktranslate %}
-
-{% endautoescape %}
diff --git a/wger/core/tests/test_password_reset.py b/wger/core/tests/test_password_reset.py
new file mode 100644
index 000000000..d047ea3c8
--- /dev/null
+++ b/wger/core/tests/test_password_reset.py
@@ -0,0 +1,95 @@
+# This file is part of wger Workout Manager.
+#
+# wger Workout Manager is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Affero General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# wger Workout Manager is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU Affero General Public License
+
+# Standard Library
+import re
+
+# Django
+from django.conf import settings
+from django.contrib.auth.models import User
+from django.core import mail
+from django.test import override_settings
+from django.urls import reverse
+
+# wger
+from wger.core.tests.base_testcase import WgerTestCase
+
+
+class PasswordResetTestCase(WgerTestCase):
+ """
+ Password reset via allauth
+ """
+
+ def test_links_point_to_allauth(self):
+ """
+ The login page links to allauth's reset form, the old URL redirects there
+ """
+ reset_url = reverse('account_reset_password')
+
+ response = self.client.get(reverse('core:user:login'))
+ self.assertContains(response, f'href="{reset_url}"')
+
+ response = self.client.get(reverse('core:user:password_reset'))
+ self.assertRedirects(response, reset_url)
+
+ def test_rate_limited(self):
+ """
+ Requests for the same address are rate-limited
+ """
+ url = reverse('account_reset_password')
+ for _ in range(5):
+ response = self.client.post(url, {'email': '[email protected]'})
+ self.assertEqual(response.status_code, 302)
+
+ response = self.client.post(url, {'email': '[email protected]'})
+ self.assertEqual(response.status_code, 429)
+
+ @override_settings(WGER_SETTINGS={**settings.WGER_SETTINGS, 'USE_RECAPTCHA': True})
+ def test_captcha_on(self):
+ """
+ The reset form has a reCAPTCHA field when USE_RECAPTCHA is set
+ """
+ response = self.client.get(reverse('account_reset_password'))
+
+ self.assertIn('captcha', response.context['form'].fields)
+ self.assertNotContains(response, 'name="submit"')
+
+ @override_settings(WGER_SETTINGS={**settings.WGER_SETTINGS, 'USE_RECAPTCHA': False})
+ def test_captcha_off(self):
+ """
+ The reset form has no reCAPTCHA field when USE_RECAPTCHA is not set
+ """
+ response = self.client.get(reverse('account_reset_password'))
+
+ self.assertNotIn('captcha', response.context['form'].fields)
+
+ def test_reset_from_email_link(self):
+ """
+ The link in the email leads to wger's form for the new password
+ """
+ self.client.post(reverse('account_reset_password'), {'email': '[email protected]'})
+ self.assertEqual(len(mail.outbox), 1)
+ link = re.search(r'https?://\S+/account/password/reset/key/\S+/', mail.outbox[0].body)
+
+ response = self.client.get(link.group(0), follow=True)
+ self.assertTemplateUsed(response, 'account/password_reset_from_key.html')
+ self.assertIn('password1', response.context['form'].fields)
+
+ response = self.client.post(
+ response.redirect_chain[-1][0],
+ {'password1': 'Sup3r-Secret-pw!', 'password2': 'Sup3r-Secret-pw!'},
+ follow=True,
+ )
+ self.assertTemplateUsed(response, 'account/password_reset_from_key_done.html')
+ self.assertTrue(User.objects.get(username='admin').check_password('Sup3r-Secret-pw!'))
diff --git a/wger/core/urls.py b/wger/core/urls.py
index dcf93008a..38c1b67a0 100644
--- a/wger/core/urls.py
+++ b/wger/core/urls.py
@@ -16,12 +16,11 @@
# Django
from django.conf.urls import include
-from django.contrib.auth import views
-from django.urls import (
- path,
- re_path,
+from django.urls import path
+from django.views.generic import (
+ RedirectView,
+ TemplateView,
)
-from django.views.generic import TemplateView
# wger
from wger.core.views import (
@@ -88,33 +87,17 @@ patterns_user = [
path('<int:pk>/edit', user.UserEditView.as_view(), name='edit'),
path('<int:pk>/overview', user.UserDetailView.as_view(), name='overview'),
path('list', user.UserListView.as_view(), name='list'),
- # Password reset is implemented by Django, no need to cook our own soup here
- # (besides the templates)
path(
'password/change',
user.WgerPasswordChangeView.as_view(),
name='change-password',
),
+ # The password reset is handled by allauth, keep the old URL for bookmarks
path(
'password/reset/',
- user.WgerPasswordResetView.as_view(),
+ RedirectView.as_view(pattern_name='account_reset_password'),
name='password_reset',
),
- path(
- 'password/reset/done/',
- views.PasswordResetDoneView.as_view(),
- name='password_reset_done',
- ),
- re_path(
- r'^password/reset/check/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,33})$',
- user.WgerPasswordResetConfirmView.as_view(),
- name='password_reset_confirm',
- ),
- path(
- 'password/reset/complete/',
- views.PasswordResetCompleteView.as_view(),
- name='password_reset_complete',
- ),
]
# sub patterns for licenses
diff --git a/wger/core/views/user.py b/wger/core/views/user.py
index c1a3950ad..433182d86 100644
--- a/wger/core/views/user.py
+++ b/wger/core/views/user.py
@@ -28,17 +28,12 @@ from django.contrib.auth import (
logout as django_logout,
)
from django.contrib.auth.decorators import login_required
-from django.contrib.auth.forms import PasswordResetForm
from django.contrib.auth.mixins import (
LoginRequiredMixin,
PermissionRequiredMixin,
)
from django.contrib.auth.models import User
-from django.contrib.auth.views import (
- PasswordChangeView,
- PasswordResetConfirmView,
- PasswordResetView,
-)
+from django.contrib.auth.views import PasswordChangeView
from django.http import (
HttpResponseForbidden,
HttpResponseNotFound,
@@ -87,7 +82,6 @@ from rest_framework.authtoken.models import Token
# wger
from wger.core.forms import (
PasswordConfirmationForm,
- PasswordResetFormCaptcha,
UsernameConfirmationForm,
UserPersonalInformationForm,
UserPreferencesForm,
@@ -756,43 +750,6 @@ class WgerPasswordChangeView(PasswordChangeView):
return form
-class WgerPasswordResetView(PasswordResetView):
- template_name = 'form_content.html'
- email_template_name = 'registration/password_reset_email.html'
- success_url = reverse_lazy('core:user:password_reset_done')
- from_email = settings.WGER_SETTINGS['EMAIL_FROM']
-
- def get_form_class(self):
- if settings.WGER_SETTINGS['USE_RECAPTCHA']:
- return PasswordResetFormCaptcha
-
- # From django
- return PasswordResetForm
-
- def get_form(self, form_class=None):
- # Massage django's default form. Our form already has a helper.
- if not settings.WGER_SETTINGS['USE_RECAPTCHA']:
- form = super().get_form(form_class)
- form.helper = FormHelper()
- form.helper.form_class = 'wger-form'
- form.helper.add_input(Submit('submit', _('Save'), css_class='btn-success btn-block'))
- return form
-
- return super().get_form(form_class)
-
-
-class WgerPasswordResetConfirmView(PasswordResetConfirmView):
- template_name = 'form_content.html'
- success_url = reverse_lazy('core:user:login')
-
- def get_form(self, form_class=None):
- form = super().get_form(form_class)
- form.helper = FormHelper()
- form.helper.form_class = 'wger-form'
- form.helper.add_input(Submit('submit', _('Save'), css_class='btn-success btn-block'))
- return form
-
-
class WgerLoginView(AllauthLoginView):
"""
allauth's login view, with one wger carve-out: temporary (guest) users are