Skip to content

Commit

Permalink
Correct user admin editing behavior
Browse files Browse the repository at this point in the history
Provide visual indicator about editing administrative users when only
one exists. Ensure that the POST request is validated enough to not
leave the system with zero admin users.
  • Loading branch information
ross-spencer committed Oct 21, 2019
1 parent cf5f857 commit e20fd6c
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 1 deletion.
22 changes: 22 additions & 0 deletions storage_service/administration/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -222,10 +222,32 @@ class UserChangeForm(auth.forms.UserChangeForm):
""" Modifys an existing user. Inherits from django's UserChangeForm. """

def __init__(self, *args, **kwargs):
current_user = kwargs.pop("current_user", None)
self.user_being_edited = kwargs["instance"]
self.superusers = auth.get_user_model().objects.filter(is_superuser=True)
super(UserChangeForm, self).__init__(*args, **kwargs)
self.fields["is_superuser"].label = _("Administrator?")
if not (current_user and current_user.is_superuser):
# If current user is not super, do not permit editing of that.
del self.fields["is_superuser"]
elif self.superusers.count() == 1 and current_user == self.user_being_edited:
# Provide some indication that this is undesirable.
self.fields["is_superuser"].widget.attrs["readonly"] = True
del self.fields["password"]

def clean(self):
"""Validate the form to protect against potential user errors."""
if self.superusers.count() > 1:
return self.cleaned_data
try:
# Protect field from being reverted if only one superuser.
if self.user_being_edited.is_superuser:
self.cleaned_data["is_superuser"] = True
except KeyError:
# Field isn't being modified, nothing to do.
pass
return self.cleaned_data

class Meta:
model = auth.get_user_model()
fields = ("username", "first_name", "last_name", "email", "is_superuser")
Expand Down
4 changes: 3 additions & 1 deletion storage_service/administration/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,9 @@ def user_edit(request, id):

action = _("Edit User")
edit_user = get_object_or_404(get_user_model(), id=id)
user_form = settings_forms.UserChangeForm(request.POST or None, instance=edit_user)
user_form = settings_forms.UserChangeForm(
request.POST or None, instance=edit_user, current_user=request.user
)
password_form = SetPasswordForm(data=request.POST or None, user=edit_user)
if "user" in request.POST and user_form.is_valid():
user_form.save()
Expand Down

0 comments on commit e20fd6c

Please sign in to comment.