diff --git a/src/pretix/base/forms/auth.py b/src/pretix/base/forms/auth.py index 4fc801c4f4..5caa1f0e06 100644 --- a/src/pretix/base/forms/auth.py +++ b/src/pretix/base/forms/auth.py @@ -214,21 +214,36 @@ class PasswordRecoverForm(forms.Form): error_messages = { 'pw_mismatch': _("Please enter the same password twice"), } + email = forms.EmailField(max_length=255, + disabled=True, + label=_("Your email address"), + widget=forms.EmailInput( + attrs={'autocomplete': 'username'}, + )) password = forms.CharField( label=_('Password'), - widget=forms.PasswordInput, + widget=forms.PasswordInput(attrs={ + 'autocomplete': 'new-password', + }), max_length=4096, required=True ) password_repeat = forms.CharField( label=_('Repeat password'), - widget=forms.PasswordInput, + widget=forms.PasswordInput(attrs={ + 'autocomplete': 'new-password', + }), max_length=4096, ) def __init__(self, user_id=None, *args, **kwargs): - self.user_id = user_id - super().__init__(*args, **kwargs) + try: + self.user = User.objects.get(id=user_id) + except User.DoesNotExist: + self.user = None + initial = kwargs.pop('initial', {}) + initial['email'] = self.user.email + super().__init__(*args, initial=initial, **kwargs) def clean(self): password1 = self.cleaned_data.get('password', '') @@ -243,11 +258,7 @@ class PasswordRecoverForm(forms.Form): def clean_password(self): password1 = self.cleaned_data.get('password', '') - try: - user = User.objects.get(id=self.user_id) - except User.DoesNotExist: - user = None - if validate_password(password1, user=user) is not None: + if validate_password(password1, user=self.user) is not None: raise forms.ValidationError(_(password_validators_help_texts()), code='pw_invalid') return password1 @@ -307,3 +318,11 @@ class ReauthForm(forms.Form): self.error_messages['inactive'], code='inactive', ) + + +class ConfirmationCodeForm(forms.Form): + code = forms.IntegerField( + label='', + widget=forms.NumberInput(attrs={'class': 'confirmation-code-input', 'inputmode': 'numeric', 'type': 'text'}), + ) + diff --git a/src/pretix/base/forms/user.py b/src/pretix/base/forms/user.py index e52bc51a4a..5f2cb77e1c 100644 --- a/src/pretix/base/forms/user.py +++ b/src/pretix/base/forms/user.py @@ -39,37 +39,17 @@ from django.contrib.auth.password_validation import ( password_validators_help_texts, validate_password, ) from django.db.models import Q +from django.urls.base import reverse +from django.utils.safestring import mark_safe from django.utils.translation import gettext_lazy as _ from pytz import common_timezones from pretix.base.models import User from pretix.control.forms import SingleLanguageWidget +from pretix.helpers.format import format_map class UserSettingsForm(forms.ModelForm): - error_messages = { - 'duplicate_identifier': _("There already is an account associated with this email address. " - "Please choose a different one."), - 'pw_current': _("Please enter your current password if you want to change your email address " - "or password."), - 'pw_current_wrong': _("The current password you entered was not correct."), - 'pw_mismatch': _("Please enter the same password twice"), - 'rate_limit': _("For security reasons, please wait 5 minutes before you try again."), - 'pw_equal': _("Please choose a password different to your current one.") - } - - old_pw = forms.CharField(max_length=255, - required=False, - label=_("Your current password"), - widget=forms.PasswordInput()) - new_pw = forms.CharField(max_length=255, - required=False, - label=_("New password"), - widget=forms.PasswordInput()) - new_pw_repeat = forms.CharField(max_length=255, - required=False, - label=_("Repeat new password"), - widget=forms.PasswordInput()) timezone = forms.ChoiceField( choices=((a, a) for a in common_timezones), label=_("Default timezone"), @@ -93,11 +73,75 @@ class UserSettingsForm(forms.ModelForm): self.user = kwargs.pop('user') super().__init__(*args, **kwargs) self.fields['email'].required = True - if self.user.auth_backend != 'native': - del self.fields['old_pw'] - del self.fields['new_pw'] - del self.fields['new_pw_repeat'] - self.fields['email'].disabled = True + self.fields['email'].disabled = True + self.fields['email'].help_text = format_map(' {text}', { + 'text': _("Change email address"), + 'link': reverse('control:user.settings.email.change') + }) + + def clean(self): + password1 = self.cleaned_data.get('new_pw') + old_pw = self.cleaned_data.get('old_pw') + + if password1 and password1 == old_pw: + raise forms.ValidationError( + self.error_messages['pw_equal'], + code='pw_equal' + ) + + if password1: + self.instance.set_password(password1) + + return self.cleaned_data + + +class User2FADeviceAddForm(forms.Form): + name = forms.CharField(label=_('Device name'), max_length=64) + devicetype = forms.ChoiceField(label=_('Device type'), widget=forms.RadioSelect, choices=( + ('totp', _('Smartphone with the Authenticator application')), + ('webauthn', _('WebAuthn-compatible hardware token (e.g. Yubikey)')), + )) + + +class UserPasswordChangeForm(forms.Form): + error_messages = { + 'pw_current': _("Please enter your current password if you want to change your email address " + "or password."), + 'pw_current_wrong': _("The current password you entered was not correct."), + 'pw_mismatch': _("Please enter the same password twice"), + 'rate_limit': _("For security reasons, please wait 5 minutes before you try again."), + 'pw_equal': _("Please choose a password different to your current one.") + } + email = forms.EmailField(max_length=255, + disabled=True, + label=_("Your email address"), + widget=forms.EmailInput( + attrs={'autocomplete': 'username'}, + )) + old_pw = forms.CharField(max_length=255, + required=False, + label=_("Your current password"), + widget=forms.PasswordInput( + attrs={'autocomplete': 'current-password'}, + )) + new_pw = forms.CharField(max_length=255, + required=False, + label=_("New password"), + widget=forms.PasswordInput( + attrs={'autocomplete': 'new-password'}, + )) + new_pw_repeat = forms.CharField(max_length=255, + required=False, + label=_("Repeat new password"), + widget=forms.PasswordInput( + attrs={'autocomplete': 'new-password'}, + )) + + def __init__(self, *args, **kwargs): + self.user = kwargs.pop('user') + initial = kwargs.pop('initial', {}) + initial['email'] = self.user.email + super().__init__(*args, initial=initial, **kwargs) def clean_old_pw(self): old_pw = self.cleaned_data.get('old_pw') @@ -121,15 +165,6 @@ class UserSettingsForm(forms.ModelForm): return old_pw - def clean_email(self): - email = self.cleaned_data['email'] - if User.objects.filter(Q(email__iexact=email) & ~Q(pk=self.instance.pk)).exists(): - raise forms.ValidationError( - self.error_messages['duplicate_identifier'], - code='duplicate_identifier', - ) - return email - def clean_new_pw(self): password1 = self.cleaned_data.get('new_pw', '') if password1 and validate_password(password1, user=self.user) is not None: @@ -148,32 +183,24 @@ class UserSettingsForm(forms.ModelForm): code='pw_mismatch' ) - def clean(self): - password1 = self.cleaned_data.get('new_pw') - email = self.cleaned_data.get('email') - old_pw = self.cleaned_data.get('old_pw') - if (password1 or email != self.user.email) and not old_pw: + +class UserEmailChangeForm(forms.Form): + error_messages = { + 'duplicate_identifier': _("There already is an account associated with this email address. " + "Please choose a different one."), + } + new_email = forms.EmailField(label=_('New email address')) + + def __init__(self, *args, **kwargs): + self.user = kwargs.pop('user') + super().__init__(*args, **kwargs) + + def clean_new_email(self): + email = self.cleaned_data['new_email'] + if User.objects.filter(Q(email__iexact=email) & ~Q(pk=self.user.pk)).exists(): raise forms.ValidationError( - self.error_messages['pw_current'], - code='pw_current' + self.error_messages['duplicate_identifier'], + code='duplicate_identifier', ) - - if password1 and password1 == old_pw: - raise forms.ValidationError( - self.error_messages['pw_equal'], - code='pw_equal' - ) - - if password1: - self.instance.set_password(password1) - - return self.cleaned_data - - -class User2FADeviceAddForm(forms.Form): - name = forms.CharField(label=_('Device name'), max_length=64) - devicetype = forms.ChoiceField(label=_('Device type'), widget=forms.RadioSelect, choices=( - ('totp', _('Smartphone with the Authenticator application')), - ('webauthn', _('WebAuthn-compatible hardware token (e.g. Yubikey)')), - )) + return email diff --git a/src/pretix/base/migrations/0289_user_verified_email.py b/src/pretix/base/migrations/0289_user_is_verified.py similarity index 63% rename from src/pretix/base/migrations/0289_user_verified_email.py rename to src/pretix/base/migrations/0289_user_is_verified.py index 26ca154157..1c95f658e6 100644 --- a/src/pretix/base/migrations/0289_user_verified_email.py +++ b/src/pretix/base/migrations/0289_user_is_verified.py @@ -1,4 +1,4 @@ -# Generated by Django 4.2.23 on 2025-09-04 12:58 +# Generated by Django 4.2.23 on 2025-09-04 16:06 from django.db import migrations, models @@ -12,7 +12,7 @@ class Migration(migrations.Migration): operations = [ migrations.AddField( model_name="user", - name="verified_email", - field=models.EmailField(max_length=190, null=True), + name="is_verified", + field=models.BooleanField(default=True), ), ] diff --git a/src/pretix/base/models/auth.py b/src/pretix/base/models/auth.py index 56eb21dbe9..9b99c54e19 100644 --- a/src/pretix/base/models/auth.py +++ b/src/pretix/base/models/auth.py @@ -35,6 +35,7 @@ import binascii import json import operator +import random from datetime import timedelta from functools import reduce @@ -243,7 +244,7 @@ class User(AbstractBaseUser, PermissionsMixin, LoggingMixin): email = models.EmailField(unique=True, db_index=True, null=True, blank=True, verbose_name=_('Email'), max_length=190) - verified_email = models.EmailField(null=True, blank=True, verbose_name=_('Verified Email'), max_length=190) + is_verified = models.BooleanField(default=True, verbose_name=_('Verified email address')) fullname = models.CharField(max_length=255, blank=True, null=True, verbose_name=_('Full name')) is_active = models.BooleanField(default=True, @@ -355,6 +356,43 @@ class User(AbstractBaseUser, PermissionsMixin, LoggingMixin): except SendMailException: pass # Already logged + def send_confirmation_code(self, reason, email=None): + from pretix.base.services.mail import mail + + with language(self.locale): + if reason == 'email_change': + msg = str(_('to confirm changing your email address from {old_email}\nto {new_email}, use the following code:').format( + old_email=self.email, new_email=email, + )) + else: + raise Exception('Invalid confirmation code reason') + + code = "%07d" % random.randint(0, 9999999) + cache.set('user_confirmation_code:' + str(self.pk), code + ':' + reason + ':' + str(email), 1800) + + mail( + email or self.email, + _('pretix confirmation code'), + 'pretixcontrol/email/confirmation_code.txt', + { + 'user': self, + 'reason': msg, + 'code': code, + }, + event=None, + user=self, + locale=self.locale + ) + + def check_confirmation_code(self, reason, code): + stored = cache.get('user_confirmation_code:' + str(self.pk)) + if not stored: + return None + stored_code, stored_reason, email = stored.split(":", maxsplit=2) + if int(stored_code) == int(code) and stored_reason == reason: + return email + + def send_password_reset(self): from pretix.base.services.mail import mail diff --git a/src/pretix/control/templates/pretixcontrol/auth/confirmation_code.html b/src/pretix/control/templates/pretixcontrol/auth/confirmation_code.html new file mode 100644 index 0000000000..89d7e14b04 --- /dev/null +++ b/src/pretix/control/templates/pretixcontrol/auth/confirmation_code.html @@ -0,0 +1,21 @@ +{% extends "pretixcontrol/auth/base.html" %} +{% load bootstrap3 %} +{% load static %} +{% load i18n %} +{% block content %} +
+{% endblock %} diff --git a/src/pretix/control/templates/pretixcontrol/auth/recover.html b/src/pretix/control/templates/pretixcontrol/auth/recover.html index 1caf09032c..a99bd6f79f 100644 --- a/src/pretix/control/templates/pretixcontrol/auth/recover.html +++ b/src/pretix/control/templates/pretixcontrol/auth/recover.html @@ -7,6 +7,7 @@