Files
fixin.me/app/models/user.rb
barbie-bot 0daf413b47 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>
2026-03-01 06:52:14 +00:00

40 lines
1.3 KiB
Ruby

class User < ApplicationRecord
devise :database_authenticatable, :registerable, :confirmable,
:recoverable, :rememberable, :validatable
# Statuses ordered by decreasing privileges
enum :status, {
admin: 4, # admin level access
active: 3, # read-write user level access
restricted: 2, # read-only user level access
locked: 1, # disallowed to sign in due to failed logins; maintained by
# Devise :lockable
disabled: 0, # administratively disallowed to sign in
}, default: :active, validate: true
has_many :readouts, dependent: :delete_all
accepts_nested_attributes_for :readouts
has_many :quantities, dependent: :delete_all
has_many :units, dependent: :delete_all
validates :email, presence: true, uniqueness: true,
length: {maximum: type_for_attribute(:email).limit}
validates :unconfirmed_email,
length: {maximum: type_for_attribute(:unconfirmed_email).limit}
def to_s
email
end
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