forked from fixin.me/fixin.me
Prevent sole admin from deleting their account
Without this guard, the last admin in the system could delete their own account, making the application unmanageable. This adds a model method `User#sole_admin?`, a controller guard in `RegistrationsController#destroy`, and disables the delete button in the profile edit view when the current user is the only remaining admin. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -2,7 +2,11 @@ class RegistrationsController < Devise::RegistrationsController
|
||||
before_action :authenticate_user!, only: [:edit, :update, :destroy]
|
||||
|
||||
def destroy
|
||||
# TODO: Disallow/disable deletion for last admin account; update :edit view
|
||||
if current_user.sole_admin?
|
||||
redirect_back fallback_location: edit_user_registration_path,
|
||||
alert: t(".sole_admin")
|
||||
return
|
||||
end
|
||||
super
|
||||
end
|
||||
|
||||
|
||||
@@ -29,4 +29,11 @@ class User < ApplicationRecord
|
||||
def at_least(status)
|
||||
User.statuses[self.status] >= User.statuses[status]
|
||||
end
|
||||
|
||||
# Returns true when this user is the only admin account in the system.
|
||||
# Used to block actions that would leave the application without an admin
|
||||
# (account deletion, status demotion).
|
||||
def sole_admin?
|
||||
admin? && !User.admin.where.not(id: id).exists?
|
||||
end
|
||||
end
|
||||
|
||||
@@ -4,9 +4,8 @@
|
||||
<% end %>
|
||||
|
||||
<div class="rightside-area buttongrid">
|
||||
<%#= TODO: Disallow/disable deletion for last admin account, image_button_to_if %>
|
||||
<%= image_button_to t('.delete'), 'account-remove-outline', user_registration_path,
|
||||
form_class: 'tools-area', method: :delete, data: {turbo: false},
|
||||
<%= image_button_to_if !current_user.sole_admin?, t('.delete'), 'account-remove-outline',
|
||||
user_registration_path, form_class: 'tools-area', method: :delete, data: {turbo: false},
|
||||
onclick: {confirm: t('.confirm_delete')} %>
|
||||
</div>
|
||||
|
||||
|
||||
Reference in New Issue
Block a user