Skip to content

armgit / wger

Public Imported from GitHub
0

Self hosted FLOSS fitness/workout, nutrition and weight tracker

Replace the registration view with allauth's

Roland Geiderb4cf3d47acf6
diff --git a/settings/settings_global.py b/settings/settings_global.py
index 97da968a9..90188aad0 100644
--- a/settings/settings_global.py
+++ b/settings/settings_global.py
@@ -238,8 +238,12 @@ ACCOUNT_LOGIN_METHODS = {'username', 'email'}
# confirmed via the verification link.
ACCOUNT_CHANGE_EMAIL = True
-# Use wger's login form (allauth's LoginForm + the password-visibility toggle).
-ACCOUNT_FORMS = {'login': 'wger.core.forms.WgerLoginForm'}
+# Use wger's own login/signup forms (allauth's forms + the password-visibility
+# toggle, and a conditional reCAPTCHA field on signup).
+ACCOUNT_FORMS = {
+ 'login': 'wger.core.forms.WgerLoginForm',
+ 'signup': 'wger.core.forms.WgerSignupForm',
+}
# django-axes handles login brute-force protection at the backend level (it
# wraps every authenticate() call, so it also covers the API login endpoints).
diff --git a/wger/core/account_adapter.py b/wger/core/account_adapter.py
index fdb6554a2..67cfc119b 100644
--- a/wger/core/account_adapter.py
+++ b/wger/core/account_adapter.py
@@ -17,7 +17,10 @@ from datetime import timedelta
# Django
from django.conf import settings
-from django.utils import timezone
+from django.utils import (
+ timezone,
+ translation,
+)
# Third Party
from allauth.account.adapter import DefaultAccountAdapter
@@ -26,6 +29,36 @@ from allauth.account.adapter import DefaultAccountAdapter
class WgerAccountAdapter(DefaultAccountAdapter):
"""Wger Account Adapter for allauth"""
+ def is_open_for_signup(self, request):
+ return settings.WGER_SETTINGS['ALLOW_REGISTRATION']
+
+ def save_user(self, request, user, form, commit=True):
+ """
+ Create the user via allauth, then pre-fill the wger profile bits the
+ old registration view used to set (notification language, default gym).
+ """
+ # wger
+ from wger.config.models import GymConfig
+ from wger.gym.models import GymUserConfig
+ from wger.utils.language import load_language
+
+ user = super().save_user(request, user, form, commit=commit)
+ if not commit:
+ return user
+
+ profile = user.userprofile
+ profile.notification_language = load_language(translation.get_language())
+
+ gym_config = GymConfig.objects.get(pk=1)
+ if gym_config.default_gym:
+ profile.gym = gym_config.default_gym
+ profile.save()
+
+ if gym_config.default_gym:
+ GymUserConfig.objects.get_or_create(gym=gym_config.default_gym, user=user)
+
+ return user
+
def send_mail(self, template_prefix, email, context):
"""
Add token expiration info to the email context.
diff --git a/wger/core/forms.py b/wger/core/forms.py
index 99562a0c6..090cd5634 100644
--- a/wger/core/forms.py
+++ b/wger/core/forms.py
@@ -19,11 +19,11 @@ from datetime import date
# Django
from django import forms
+from django.conf import settings
from django.contrib.auth import authenticate
from django.contrib.auth.forms import (
AuthenticationForm,
PasswordResetForm,
- UserCreationForm,
)
from django.contrib.auth.models import User
from django.core.exceptions import ValidationError
@@ -39,7 +39,10 @@ from django.utils.translation import (
)
# Third Party
-from allauth.account.forms import LoginForm as AllauthLoginForm
+from allauth.account.forms import (
+ LoginForm as AllauthLoginForm,
+ SignupForm as AllauthSignupForm,
+)
from allauth.account.utils import filter_users_by_email
from crispy_forms.helper import FormHelper
from crispy_forms.layout import (
@@ -137,6 +140,48 @@ class WgerLoginForm(AllauthLoginForm):
)
+class WgerSignupForm(AllauthSignupForm):
+ """
+ allauth's signup form with wger's password-toggle widgets and an optional
+ reCAPTCHA field (shown when WGER_SETTINGS['USE_RECAPTCHA'] is set).
+
+ The crispy helper uses ``form_tag = False`` because both consumers — the
+ dedicated signup page and the landing page — provide their own ``<form>``.
+ """
+
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+
+ for name in ('password1', 'password2'):
+ if name in self.fields:
+ self.fields[name].widget = PasswordInputWithToggle()
+
+ layout_fields = [
+ 'username',
+ 'email',
+ Row(
+ Column('password1', css_class='col-md-6 col-12'),
+ Column('password2', css_class='col-md-6 col-12'),
+ css_class='form-row',
+ ),
+ ]
+ if settings.WGER_SETTINGS['USE_RECAPTCHA']:
+ self.fields['captcha'] = ReCaptchaField(
+ widget=ReCaptchaV3(action='register'),
+ 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(
+ *layout_fields,
+ ButtonHolder(Submit('submit', _('Register'), css_class='btn-success btn-block')),
+ )
+
+
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)
@@ -296,68 +341,6 @@ class PasswordConfirmationForm(Form):
return self.cleaned_data.get('password')
-class RegistrationForm(UserCreationForm, UserEmailForm):
- """
- Registration form with reCAPTCHA field
- """
-
- captcha = ReCaptchaField(
- widget=ReCaptchaV3(action='register'),
- label='reCaptcha',
- help_text=gettext_lazy('The form is secured with reCAPTCHA'),
- )
-
- def __init__(self, *args, **kwargs):
- super().__init__(*args, **kwargs)
-
- # Apply custom password widgets
- self.fields['password1'].widget = PasswordInputWithToggle()
- self.fields['password2'].widget = PasswordInputWithToggle()
-
- self.helper = FormHelper()
- self.helper.form_class = 'wger-form'
- self.helper.layout = Layout(
- 'username',
- 'email',
- Row(
- Column('password1', css_class='col-md-6 col-12'),
- Column('password2', css_class='col-md-6 col-12'),
- css_class='form-row',
- ),
- 'captcha',
- ButtonHolder(Submit('submitBtn', _('Register'), css_class='btn-success btn-block')),
- )
-
-
-class RegistrationFormNoCaptcha(UserCreationForm, UserEmailForm):
- """
- Registration form without CAPTCHA field
- """
-
- def __init__(self, *args, **kwargs):
- super().__init__(*args, **kwargs)
-
- # Apply custom password widgets
- self.fields['password1'].widget = PasswordInputWithToggle()
- self.fields['password2'].widget = PasswordInputWithToggle()
-
- self.helper = FormHelper()
- self.helper.form_class = 'wger-form'
- self.helper.layout = Layout(
- 'username',
- 'email',
- Row(
- Column('password1', css_class='col-md-6 col-12'),
- Column('password2', css_class='col-md-6 col-12'),
- css_class='form-row',
- ),
- ButtonHolder(
- Submit('submit', _('Register'), css_class='btn-success col-sm-6 col-12'),
- css_class='text-center',
- ),
- )
-
-
class PasswordResetFormCaptcha(PasswordResetForm):
captcha = ReCaptchaField(
widget=ReCaptchaV3(action='password_reset'),
diff --git a/wger/core/templates/account/signup.html b/wger/core/templates/account/signup.html
new file mode 100644
index 000000000..1e58328f4
--- /dev/null
+++ b/wger/core/templates/account/signup.html
@@ -0,0 +1,34 @@
+{% extends "base.html" %}
+{% load i18n wger_extras crispy_forms_tags %}
+
+{% block title %}{% translate "Register" %}{% endblock %}
+
+
+{% block header %}
+{% endblock %}
+
+
+{% block content %}
+ <form method="post" action="{% url 'core:user:registration' %}">
+ {% csrf_token %}
+ {% if redirect_field_value %}
+ <input type="hidden"
+ name="{{ redirect_field_name }}"
+ value="{{ redirect_field_value }}">
+ {% endif %}
+ {% crispy form %}
+ </form>
+{% endblock %}
+
+
+{% block sidebar %}
+ {% if user.is_anonymous %}
+ <h4>{% translate "Already have an account?" %}</h4>
+ <p>
+ <a href="{% url 'core:user:login' %}">
+ <span class="{% fa_class 'sign-in-alt' %}"></span>
+ {% translate "Login" %}
+ </a>
+ </p>
+ {% endif %}
+{% endblock %}
diff --git a/wger/core/templates/user/registration_sidebar.html b/wger/core/templates/user/registration_sidebar.html
deleted file mode 100644
index c39cb9605..000000000
--- a/wger/core/templates/user/registration_sidebar.html
+++ /dev/null
@@ -1,17 +0,0 @@
-
-{% load i18n static wger_extras crispy_forms_tags %}
-
-
-
-{% block sidebar %}
-{% if user.is_anonymous %}
- <h4>{% trans "Already have an account?" %}</h4>
- <p>
- <a href="{% url 'core:user:login' %}">
- <span class="{% fa_class 'sign-in-alt' %}"></span>
- {% trans "Login" %}
- </a>
- </p>
-{% endif %}
-{% endblock %}
-
diff --git a/wger/core/tests/test_registration.py b/wger/core/tests/test_registration.py
index 4002bdb66..f104dcaf9 100644
--- a/wger/core/tests/test_registration.py
+++ b/wger/core/tests/test_registration.py
@@ -33,10 +33,6 @@ from rest_framework.status import (
)
# wger
-from wger.core.forms import (
- RegistrationForm,
- RegistrationFormNoCaptcha,
-)
from wger.core.tests.base_testcase import WgerTestCase
@@ -50,8 +46,7 @@ class RegistrationTestCase(WgerTestCase):
def test_registration_captcha(self):
"""
- Tests that the correct form is used depending on global
- configuration settings
+ The signup form shows a reCAPTCHA field only when USE_RECAPTCHA is set.
"""
with self.settings(
WGER_SETTINGS={
@@ -63,7 +58,7 @@ class RegistrationTestCase(WgerTestCase):
}
):
response = self.client.get(reverse('core:user:registration'))
- self.assertIsInstance(response.context['form'], RegistrationForm)
+ self.assertIn('captcha', response.context['form'].fields)
with self.settings(
WGER_SETTINGS={
@@ -75,7 +70,7 @@ class RegistrationTestCase(WgerTestCase):
}
):
response = self.client.get(reverse('core:user:registration'))
- self.assertIsInstance(response.context['form'], RegistrationFormNoCaptcha)
+ self.assertNotIn('captcha', response.context['form'].fields)
def test_register(self):
# Fetch the registration page
diff --git a/wger/core/urls.py b/wger/core/urls.py
index 24f7e7306..4e63ebdce 100644
--- a/wger/core/urls.py
+++ b/wger/core/urls.py
@@ -72,7 +72,7 @@ patterns_user = [
path('delete', user.delete, name='delete'),
path('<int:user_pk>/delete', user.delete, name='delete'),
path('<int:user_pk>/trainer-login', user.trainer_login, name='trainer-login'),
- path('registration', user.registration, name='registration'),
+ path('registration', user.WgerSignupView.as_view(), name='registration'),
path('preferences', user.preferences, name='preferences'),
path('api-key', user.api_key, name='api-key'),
path('demo-entries', misc.demo_entries, name='demo-entries'),
diff --git a/wger/core/views/user.py b/wger/core/views/user.py
index 9c139116b..40923d9a4 100644
--- a/wger/core/views/user.py
+++ b/wger/core/views/user.py
@@ -21,7 +21,6 @@ import logging
from django.conf import settings
from django.contrib import messages
from django.contrib.auth import (
- authenticate,
login as django_login,
logout as django_logout,
)
@@ -51,7 +50,6 @@ from django.urls import (
reverse,
reverse_lazy,
)
-from django.utils import translation
from django.utils.http import url_has_allowed_host_and_scheme
from django.utils.translation import (
gettext as _,
@@ -67,8 +65,10 @@ from django.views.generic import (
# Third Party
from allauth.account.mixins import RedirectAuthenticatedUserMixin
-from allauth.account.models import EmailAddress
-from allauth.account.views import LoginView as AllauthLoginView
+from allauth.account.views import (
+ LoginView as AllauthLoginView,
+ SignupView as AllauthSignupView,
+)
from crispy_forms.helper import FormHelper
from crispy_forms.layout import (
ButtonHolder,
@@ -80,12 +80,9 @@ from crispy_forms.layout import (
from rest_framework.authtoken.models import Token
# wger
-from wger.config.models import GymConfig
from wger.core.forms import (
PasswordConfirmationForm,
PasswordResetFormCaptcha,
- RegistrationForm,
- RegistrationFormNoCaptcha,
UserPersonalInformationForm,
UserPreferencesForm,
)
@@ -93,7 +90,6 @@ from wger.gym.helpers import is_same_gym
from wger.gym.models import (
AdminUserNote,
Contract,
- GymUserConfig,
)
from wger.manager.models import (
Routine,
@@ -110,7 +106,6 @@ from wger.utils.generic_views import (
WgerFormMixin,
WgerMultiplePermissionRequiredMixin,
)
-from wger.utils.language import load_language
from wger.weight.models import WeightEntry
@@ -247,81 +242,26 @@ def logout(request):
return HttpResponseRedirect(reverse('core:user:login'))
-def registration(request):
- """
- A form to allow for registration of new users
+class WgerSignupView(AllauthSignupView):
"""
+ allauth's signup view, with two wger carve-outs: registration disabled
+ globally redirects to the features page (instead of allauth's "signup
+ closed" page), and temporary (guest) users may still reach the
+ registration page so they can create a real account.
- # If global user registration is deactivated, redirect
- if not settings.WGER_SETTINGS['ALLOW_REGISTRATION']:
- return HttpResponseRedirect(reverse('software:features'))
-
- template_data = {}
- template_data.update(csrf(request))
-
- # Don't show captcha if the global parameter is false
- FormClass = (
- RegistrationForm if settings.WGER_SETTINGS['USE_RECAPTCHA'] else RegistrationFormNoCaptcha
- )
-
- # Redirect regular users, in case they reached the registration page
- if request.user.is_authenticated and not request.user.userprofile.is_temporary:
- return HttpResponseRedirect(reverse('core:dashboard'))
-
- if request.method == 'POST':
- form = FormClass(data=request.POST)
-
- # If the data is valid, log in and redirect
- if form.is_valid():
- username = form.cleaned_data['username']
- password = form.cleaned_data['password1']
- email = form.cleaned_data['email']
- user = User.objects.create_user(username, email, password)
- user.save()
-
- # Pre-set some values of the user's profile
- language = load_language(translation.get_language())
- user.userprofile.notification_language = language
-
- # Set default gym, if needed
- gym_config = GymConfig.objects.get(pk=1)
- if gym_config.default_gym:
- user.userprofile.gym = gym_config.default_gym
-
- # Create gym user configuration object
- config = GymUserConfig()
- config.gym = gym_config.default_gym
- config.user = user
- config.save()
-
- user.userprofile.save()
- user = authenticate(request=request, username=username, password=password)
-
- # Log the user in
- django_login(request, user)
-
- # Email the user with the activation link
- if email:
- EmailAddress.objects.add_email(
- request,
- request.user,
- request.user.email,
- confirm=True,
- )
-
- # Redirect to the dashboard
- messages.success(request, _('You were successfully registered'))
- return HttpResponseRedirect(reverse('core:dashboard'))
- else:
- form = FormClass()
-
- template_data['form'] = form
- template_data['title'] = _('Register')
-
- # Add this line to use the new registration-specific sidebar
- template_data['sidebar'] = 'user/registration_sidebar.html'
+ The wger-specific profile setup (notification language, default gym) lives
+ in WgerAccountAdapter.save_user().
+ """
- return render(request, 'form_content.html', template_data)
+ def dispatch(self, request, *args, **kwargs):
+ if not settings.WGER_SETTINGS['ALLOW_REGISTRATION']:
+ return HttpResponseRedirect(reverse('software:features'))
+ if request.user.is_authenticated and request.user.userprofile.is_temporary:
+ # Skip RedirectAuthenticatedUserMixin's "already logged in" redirect
+ return super(RedirectAuthenticatedUserMixin, self).dispatch(
+ request, *args, **kwargs
+ )
+ return super().dispatch(request, *args, **kwargs)
@login_required
diff --git a/wger/software/views.py b/wger/software/views.py
index bcdac4fe1..6991ecc04 100644
--- a/wger/software/views.py
+++ b/wger/software/views.py
@@ -25,10 +25,7 @@ from django.shortcuts import render
import requests
# wger
-from wger.core.forms import (
- RegistrationForm,
- RegistrationFormNoCaptcha,
-)
+from wger.core.forms import WgerSignupForm
from wger.exercises.models import Exercise
from wger.nutrition.models import Ingredient
@@ -70,10 +67,7 @@ def features(request):
context = fetch_github_stats()
- FormClass = (
- RegistrationForm if settings.WGER_SETTINGS['USE_RECAPTCHA'] else RegistrationFormNoCaptcha
- )
- form = FormClass()
+ form = WgerSignupForm()
form.fields['username'].widget.attrs.pop('autofocus', None)
context['form'] = form