Skip to contentSkip to conversation

Let maintainers change their email address safely

PATCH New Tim Orling 1 participant 3 messages Nov 14

lore
Share & tools
lore

Tim Orling

author
#0 lore raw

cover Let maintainers change their email address safely

Bug 11195: a maintainer who changes the email address on their profile loses access to their layers, because edit rights come from matching the user's address against the layers' maintainer records.

Moving the maintainer records to the new address moves edit rights, so this is done carefully. Changing the email already logs the user out and needs the new address to be confirmed. On top of that:
- changing the email now needs the current password, so a logged-in session alone is not enough, and the old address is told about it;
- the maintainer records only move after an admin approves it, with the "Approve moving maintainer records" action on the user's profile; the admins are emailed when a confirmed change is waiting.
Users who don't maintain layers are not held up.

1: The profile page had no login check, so a visitor who was not
logged in got an Internal Server Error instead of the login page.
2: The maintainer email change itself (bug 11195). It adds migration
0057, so it applies on top of "[PATCH 0/2] Remove dependencies dropped from conf/layer.conf" (bug 14348), which adds 0056.

The test suite passes in the Docker image at each patch (83 passed, 1 skipped at the end); the tests go through the profile form, the activation link and the admin action.

Tim Orling (2):
layerindex/views: require login for the profile page
layerindex: let a maintainer keep their layers when they change email

 layerindex/admin.py                           | 26 ++++-
 layerindex/forms.py                           |  8 ++
 .../0057_userprofile_previous_email.py        | 16 ++++
 layerindex/models.py                          | 20 ++++
 layerindex/views.py                           | 45 ++++++++-
 tests/test_profile_email.py                   | 94 +++++++++++++++++--
 6 files changed, 200 insertions(+), 9 deletions(-)
 create mode 100644 layerindex/migrations/0057_userprofile_previous_email.py

base-commit: 08e58cdece30019a6f9e5d14af16ebe20afa6177
prerequisite-patch-id: 6c677e4190187d389840d2a94b4d857a69c0d647
prerequisite-patch-id: 282bc018dfe6528deb8363d3cbd1b31671c4b606

Signature · 1 line
2.56.0
author
#1 lore raw

PATCH 1/2 layerindex/views: require login for the profile page

The profile page had no login check of its own, so a visitor who was not logged in got an Internal Server Error (500) for both GET and POST instead of the login page. Require login.

AI-Generated: Claude Opus 5.5

---
 layerindex/views.py         | 3 ++-
 tests/test_profile_email.py | 9 +++++++++
 2 files changed, 11 insertions(+), 1 deletion(-)
layerindex/views.py +2 -1
index 592311f..35186e6 100644
@@ -19,6 +19,7 @@ from django import forms
 from django.contrib import messages
 from django.contrib.auth import logout
 from django.contrib.auth.decorators import login_required
+from django.contrib.auth.mixins import LoginRequiredMixin
 from django.contrib.auth.hashers import make_password
 from django.contrib.auth.models import Permission, User
 from django.contrib.messages.views import SuccessMessageMixin
@@ -1001,7 +1002,7 @@ class HistoryListView(ListView):
         return Revision.objects.all().order_by('-date_created')
 
 
-class EditProfileFormView(SuccessMessageMixin, UpdateView):
+class EditProfileFormView(LoginRequiredMixin, SuccessMessageMixin, UpdateView):
     form_class = EditProfileForm
 
     @method_decorator(never_cache)
tests/test_profile_email.py +9 -0
index 79e4adf..57feee5 100644
@@ -65,3 +65,12 @@ class TestProfileEmailChange(TestCase):
         self.user.refresh_from_db()
         self.assertTrue(self.user.is_active)
         self.assertEqual(len(mail.outbox), 0)
+
+    def test_profile_requires_login(self):
+        self.client.logout()
+        for method in ('get', 'post'):
+            response = getattr(self.client, method)(reverse('profile'))
+            self.assertEqual(response.status_code, 302, method)
+            self.assertIn(reverse('login'), response['Location'])
+        self.user.refresh_from_db()
+        self.assertEqual(self.user.email, '[email protected]')
Signature · 1 line
2.56.0
author
#2 lore raw

PATCH 2/2 layerindex: let a maintainer keep their layers when they change email

In reply to Tim Orling

Edit rights on a layer come from matching the user's email address against the layer's maintainer records, so a maintainer who changed the address on their profile lost access to their layers, and an admin had to change the maintainer records of every layer branch by hand.

Remember the confirmed address when the email is changed. Once the new address is confirmed through the activation link, ask the site admins to approve moving the maintainer records to it, and move them when an admin runs "Approve moving maintainer records" on the user's profile; the user is emailed then.

Since that moves edit rights, make changing the email address need the current password, so that a logged-in session alone is not enough, and tell the old address about the change.

[YOCTO #11195]

AI-Generated: Claude Opus 5.5

---
 layerindex/admin.py                           | 26 +++++-
 layerindex/forms.py                           |  8 ++
 .../0057_userprofile_previous_email.py        | 16 ++++
 layerindex/models.py                          | 20 +++++
 layerindex/views.py                           | 42 +++++++++
 tests/test_profile_email.py                   | 85 +++++++++++++++++--
 6 files changed, 189 insertions(+), 8 deletions(-)
 create mode 100644 layerindex/migrations/0057_userprofile_previous_email.py
layerindex/admin.py +24 -2
index f8b2f6e..226f43f 100644
@@ -7,7 +7,8 @@
 # SPDX-License-Identifier: MIT
 
 from layerindex.models import *
-from django.contrib import admin
+from django.conf import settings
+from django.contrib import admin, messages
 from reversion_compare.admin import CompareVersionAdmin
 from django.forms import TextInput
 from django.contrib.sites.models import Site
@@ -238,4 +239,25 @@ admin.site.register(PythonEnvironment)
 admin.site.register(SiteNotice)
 admin.site.register(SecurityQuestion)
 admin.site.register(SecurityQuestionAnswer)
-admin.site.register(UserProfile)
+class UserProfileAdmin(admin.ModelAdmin):
+    list_display = ('user', 'previous_email')
+    search_fields = ('user__username', 'user__email', 'previous_email')
+    actions = ['approve_maintainer_email_change']
+
+    @admin.action(description='Approve moving maintainer records to the new email address')
+    def approve_maintainer_email_change(self, request, queryset):
+        from django.core.mail import send_mail
+        for profile in queryset.exclude(previous_email=''):
+            user = profile.user
+            if not user.is_active:
+                # The new address hasn't been confirmed yet
+                self.message_user(request, '%s has not confirmed their new address yet; nothing moved' % user.username, messages.WARNING)
+                continue
+            moved = profile.move_maintainer_records()
+            if moved:
+                send_mail('Maintainer email address updated on %s' % Site.objects.get_current().name,
+                          'Your maintainer records were moved to %s for:\n\n  %s\n' % (user.email, '\n  '.join(moved)),
+                          settings.DEFAULT_FROM_EMAIL, [user.email])
+            self.message_user(request, 'Moved %d maintainer records of %s to %s' % (len(moved), user.username, user.email))
+
+admin.site.register(UserProfile, UserProfileAdmin)
layerindex/forms.py +8 -0
index 733adc2..7fcdbb0 100644
@@ -211,6 +211,9 @@ class EditNoteForm(StyledModelForm):
 
 
 class EditProfileForm(StyledModelForm):
+    current_password = forms.CharField(label='Current password', required=False, strip=False,
+                                       widget=forms.PasswordInput(attrs={'autocomplete': 'current-password'}),
+                                       help_text='Needed to change your email address')
     captcha = CaptchaField(label='Verification', help_text='Please enter the letters displayed for verification purposes', error_messages={'invalid':'Incorrect entry, please try again'})
     security_question_1 = forms.ModelChoiceField(queryset=SecurityQuestion.objects.all())
     answer_1 = forms.CharField(widget=forms.TextInput(), label='Answer', initial="*****")
@@ -265,6 +268,11 @@ class EditProfileForm(StyledModelForm):
 
     def clean(self):
         cleaned_data = super(EditProfileForm, self).clean()
+        # A logged-in session alone must not be enough to change the address
+        # that layer edit rights and password resets are tied to
+        if 'email' in self.changed_data:
+            if not self.instance.check_password(cleaned_data.get('current_password') or ''):
+                self.add_error('current_password', 'Enter your current password to change your email address')
         for data in self.changed_data:
             # Check if a security answer has been updated. If one is updated, they must all be
             # and each security question must be unique.
layerindex/migrations/0057_userprofile_previous_email.py new file +16 -0
new file mode 100644
index 0000000..495fee8
@@ -0,0 +1,16 @@
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+    dependencies = [
+        ('layerindex', '0056_layerdependency_from_layer_conf'),
+    ]
+
+    operations = [
+        migrations.AddField(
+            model_name='userprofile',
+            name='previous_email',
+            field=models.CharField(blank=True, max_length=255),
+        ),
+    ]
layerindex/models.py +20 -0
index fd8e88f..883168c 100644
@@ -962,6 +962,26 @@ class SecurityQuestion(models.Model):
 class UserProfile(models.Model):
     user = models.OneToOneField(User, on_delete=models.CASCADE)
     answer_attempts = models.IntegerField(default=0)
+    # The confirmed email address before a change of address that has not
+    # been confirmed yet, to move the user's maintainer records once it is
+    previous_email = models.CharField(max_length=255, blank=True)
+
+    def pending_maintainer_records(self):
+        """Maintainer records still under the user's previous address"""
+        if not self.previous_email or self.previous_email.strip().lower() == self.user.email.strip().lower():
+            return LayerMaintainer.objects.none()
+        return LayerMaintainer.objects.filter(email__iexact=self.previous_email.strip())
+
+    def move_maintainer_records(self):
+        """Move the maintainer records to the user's current address. Returns
+        the layer branches they are for, as "layer (branch)"."""
+        maintainers = self.pending_maintainer_records()
+        moved = sorted('%s (%s)' % (m.layerbranch.layer.name, m.layerbranch.branch.name)
+                       for m in maintainers.select_related('layerbranch__layer', 'layerbranch__branch'))
+        maintainers.update(email=self.user.email)
+        self.previous_email = ''
+        self.save(update_fields=['previous_email'])
+        return moved
 
     def __str__(self):
         return '%s' % (self.user)
layerindex/views.py +42 -0

66 lines not on this page · raw message

tests/test_profile_email.py +79 -6

115 lines not on this page · raw message

Signature · 1 line
2.56.0