admin: user management, invites, password reset, audit log
Add /admin/users to create, edit, disable and delete accounts with the per-area permission grid. New users get a one-time invite link (48 h) by email; the admin also sees it once, so an account without email can still be onboarded. Forgotten passwords get a 1 h reset link with the same answer for unknown accounts. Only token hashes are stored. Guards against escalation and lockout: a user manager can only grant flags they hold and cannot touch flags they lack; only superusers change superuser accounts; nobody can disable or delete themselves; the last active superuser stays. Logins, user changes, and bingo and invoice actions are recorded in an audit log at /admin/audit. Read timestamps as UTC: they are all written with Time.now.utc, and on a UTC+4 host a fresh 1 h token read back as already expired. Assisted-by: Claude:opus-5
This commit is contained in:
parent
8471570187
commit
d91a72f603
17 changed files with 686 additions and 0 deletions
|
|
@ -54,6 +54,10 @@ module AdminAuth
|
|||
Rack::Utils.secure_compare(p, pass.to_s)
|
||||
end
|
||||
|
||||
def audit!(action, target = nil, detail = nil, user: current_user)
|
||||
Audit.log(action: action, user: user, target: target, detail: detail, ip: client_ip)
|
||||
end
|
||||
|
||||
def safe_next(target)
|
||||
target.to_s.match?(%r{\A/admin(/[\w\-/]*)?\z}) ? target : '/admin'
|
||||
end
|
||||
|
|
@ -102,12 +106,15 @@ module AdminAuth
|
|||
user.password = ENV['ADMIN_PASSWORD']
|
||||
user.save
|
||||
$logger.warn("users: emergency login restored superuser #{name} from #{client_ip}")
|
||||
audit!('auth.emergency_login', name, user: user)
|
||||
end
|
||||
if user
|
||||
log_in!(user)
|
||||
audit!('auth.login')
|
||||
redirect @next
|
||||
else
|
||||
$logger.info("users: failed login for #{params[:username].to_s[0, 64].inspect} from #{client_ip}")
|
||||
Audit.log(action: 'auth.login_failed', username: params[:username].to_s[0, 64], ip: client_ip)
|
||||
@error = 'Wrong username or password.'
|
||||
status 401
|
||||
erb :'admin/login'
|
||||
|
|
@ -115,6 +122,7 @@ module AdminAuth
|
|||
end
|
||||
|
||||
app.post '/admin/logout' do
|
||||
audit!('auth.logout') if current_user
|
||||
session.clear
|
||||
redirect '/admin/login'
|
||||
end
|
||||
|
|
@ -143,6 +151,7 @@ module AdminAuth
|
|||
u.session_version += 1 # other sessions out
|
||||
u.save
|
||||
log_in!(u)
|
||||
audit!('auth.password_changed')
|
||||
redirect '/admin'
|
||||
end
|
||||
end
|
||||
|
|
|
|||
20
lib/audit.rb
Normal file
20
lib/audit.rb
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
require 'sequel'
|
||||
|
||||
# Append-only record of who changed what in the admin (/admin/audit).
|
||||
module Audit
|
||||
module_function
|
||||
|
||||
def log(action:, user: nil, target: nil, detail: nil, ip: nil, username: nil)
|
||||
DB.connection[:audit_log].insert(
|
||||
user_id: user&.id, username: user&.username || username, action: action,
|
||||
target: target&.to_s&.slice(0, 200), detail: detail&.to_s&.slice(0, 2000),
|
||||
ip: ip, created_at: Time.now.utc
|
||||
)
|
||||
rescue Sequel::Error => e
|
||||
$logger.error("audit: #{action} not recorded: #{e.message}") # never break the action itself
|
||||
end
|
||||
|
||||
def recent(limit = 200)
|
||||
DB.connection[:audit_log].order(Sequel.desc(:created_at), Sequel.desc(:id)).limit(limit).all
|
||||
end
|
||||
end
|
||||
|
|
@ -72,6 +72,7 @@ module BingoAdmin
|
|||
@dc.position = Bingo::Datacenter.count + 1
|
||||
@dc.save
|
||||
Bingo.place!(@dc, position_param)
|
||||
audit!('bingo.dc_create', @dc.slug, "##{@dc.refresh.position} #{@dc.name_ru}")
|
||||
session[:bingo_flash] = "Added #{@dc.name_ru} at ##{@dc.refresh.position}."
|
||||
redirect "/admin/bingo/dc/#{@dc.id}"
|
||||
end
|
||||
|
|
@ -90,6 +91,7 @@ module BingoAdmin
|
|||
if errs.empty?
|
||||
dc.save_changes
|
||||
Bingo.place!(dc, position_param) if position_param && position_param != dc.position
|
||||
audit!('bingo.dc_update', dc.slug, dc.name_ru)
|
||||
session[:bingo_flash] = 'Saved.'
|
||||
else
|
||||
session[:bingo_flash] = errs.join('; ')
|
||||
|
|
@ -106,12 +108,14 @@ module BingoAdmin
|
|||
dc.destroy
|
||||
Bingo.renumber!
|
||||
end
|
||||
audit!('bingo.dc_delete', dc.slug, "#{dc.name_ru}, #{n} incident(s)")
|
||||
session[:bingo_flash] = "Deleted #{dc.name_ru}#{" and #{n} incident(s)" if n.positive?}."
|
||||
redirect '/admin/bingo'
|
||||
end
|
||||
|
||||
app.post '/admin/bingo/sort' do
|
||||
Bingo.sort_by_mw!
|
||||
audit!('bingo.sort_by_mw')
|
||||
session[:bingo_flash] = 'Sorted by MW (unknown last).'
|
||||
redirect '/admin/bingo'
|
||||
end
|
||||
|
|
@ -130,6 +134,7 @@ module BingoAdmin
|
|||
end
|
||||
dc.save_changes
|
||||
Bingo::Photo.attach(dc, bytes)
|
||||
audit!('bingo.photo_store', dc.slug, dc.photo_source_url)
|
||||
session[:bingo_flash] = dc.photo_variants ? 'Photo stored.' : 'Photo stored (no resized variants; check logs).'
|
||||
rescue Bingo::Photo::Error => e
|
||||
session[:bingo_flash] = "Photo failed: #{e.message}"
|
||||
|
|
@ -140,6 +145,7 @@ module BingoAdmin
|
|||
app.post '/admin/bingo/dc/:id/photo/delete' do
|
||||
dc = Bingo::Datacenter[params[:id].to_i] or halt 404
|
||||
dc.update(photo_key: nil, photo_variants: false)
|
||||
audit!('bingo.photo_remove', dc.slug)
|
||||
session[:bingo_flash] = 'Photo removed from card (object kept in bucket).'
|
||||
redirect "/admin/bingo/dc/#{dc.id}"
|
||||
end
|
||||
|
|
@ -156,6 +162,7 @@ module BingoAdmin
|
|||
rescue Bingo::Photo::Error => e
|
||||
failed << "#{dc.slug}: #{e.message}"
|
||||
end
|
||||
audit!('bingo.photos_import', params[:all] == '1' ? 'all' : 'missing', "#{ok} ok, #{failed.size} failed")
|
||||
session[:bingo_flash] = (["Imported #{ok}."] + failed).join(' | ')
|
||||
redirect '/admin/bingo'
|
||||
end
|
||||
|
|
@ -171,6 +178,7 @@ module BingoAdmin
|
|||
$logger.error("bingo: rebuild #{dc.slug}: #{e.class}: #{e.message}")
|
||||
end
|
||||
failed = dcs.reject(&:photo_variants).map { |dc| errors[dc.slug] ? "#{dc.slug} (#{errors[dc.slug]})" : dc.slug }
|
||||
audit!('bingo.photos_rebuild', nil, "#{dcs.size - failed.size}/#{dcs.size}")
|
||||
session[:bingo_flash] = "Rebuilt #{dcs.size - failed.size}/#{dcs.size}.#{" Failed: #{failed.join(', ')}" if failed.any?}"
|
||||
redirect '/admin/bingo'
|
||||
end
|
||||
|
|
@ -203,6 +211,7 @@ module BingoAdmin
|
|||
title_ru: params[:title_ru].strip, title_en: blank_nil(params[:title_en]),
|
||||
title_uk: blank_nil(params[:title_uk]), url: blank_nil(url)
|
||||
)
|
||||
audit!('bingo.incident_create', dc.slug, "#{date} #{params[:kind]}: #{params[:title_ru].strip}")
|
||||
session[:bingo_flash] = "Incident recorded for #{dc.name_ru}."
|
||||
else
|
||||
session[:bingo_flash] = errs.join('; ')
|
||||
|
|
@ -211,7 +220,9 @@ module BingoAdmin
|
|||
end
|
||||
|
||||
app.post '/admin/bingo/incidents/:id/delete' do
|
||||
inc = Bingo::Incident[params[:id].to_i]
|
||||
Bingo::Incident.where(id: params[:id].to_i).delete
|
||||
audit!('bingo.incident_delete', inc&.datacenter&.slug, inc && "#{inc.occurred_on} #{inc.title_ru}")
|
||||
session[:bingo_flash] = 'Incident deleted.'
|
||||
redirect '/admin/bingo'
|
||||
end
|
||||
|
|
|
|||
|
|
@ -4,6 +4,9 @@ module DB
|
|||
module_function
|
||||
|
||||
def connect!
|
||||
# Every timestamp is written as Time.now.utc; read them back as UTC too
|
||||
# (otherwise a host in UTC+4 sees a fresh 1 h token as already expired).
|
||||
Sequel.default_timezone = :utc
|
||||
@connection ||= Sequel.connect(
|
||||
ENV.fetch('DATABASE_URL'),
|
||||
max_connections: 5,
|
||||
|
|
|
|||
|
|
@ -69,4 +69,33 @@ module Mailer
|
|||
body body
|
||||
end
|
||||
end
|
||||
|
||||
# Invite / password-reset email with a one-time link.
|
||||
def account_link(to:, username:, url:, kind:)
|
||||
from = ENV.fetch('MAIL_FROM')
|
||||
subj, intro, ttl =
|
||||
if kind == 'invite'
|
||||
['Your asxp.io admin account', "An account \"#{username}\" was created for you on the asxp.io admin.\nSet your password here:", '48 hours']
|
||||
else
|
||||
['Reset your asxp.io admin password', "Someone (hopefully you) asked to reset the password for \"#{username}\".\nSet a new one here:", '1 hour']
|
||||
end
|
||||
body = <<~BODY
|
||||
#{intro}
|
||||
|
||||
#{url}
|
||||
|
||||
The link works once and expires in #{ttl}. If you didn't expect this
|
||||
email, ignore it.
|
||||
|
||||
--
|
||||
asxp.io
|
||||
BODY
|
||||
|
||||
Mail.deliver do
|
||||
from from
|
||||
to to
|
||||
subject subj
|
||||
body body
|
||||
end
|
||||
end
|
||||
end
|
||||
|
|
|
|||
27
lib/user.rb
27
lib/user.rb
|
|
@ -85,3 +85,30 @@ class UserPermission < Sequel::Model(:user_permissions)
|
|||
unrestrict_primary_key
|
||||
many_to_one :user
|
||||
end
|
||||
|
||||
# One-time invite / reset links; see migration 008.
|
||||
class UserToken < Sequel::Model(:user_tokens)
|
||||
TTL = { 'invite' => 48 * 3600, 'reset' => 3600 }.freeze
|
||||
|
||||
many_to_one :user
|
||||
|
||||
def self.digest(raw) = OpenSSL::Digest::SHA256.hexdigest(raw.to_s)
|
||||
|
||||
# Returns the raw token; earlier unused tokens of the same purpose die.
|
||||
def self.issue!(user, purpose)
|
||||
where(user_id: user.id, purpose: purpose, used_at: nil).delete
|
||||
raw = SecureRandom.urlsafe_base64(32)
|
||||
create(user_id: user.id, purpose: purpose, token_digest: digest(raw),
|
||||
expires_at: Time.now.utc + TTL.fetch(purpose), created_at: Time.now.utc)
|
||||
raw
|
||||
end
|
||||
|
||||
def self.find_valid(raw, purpose)
|
||||
t = self[token_digest: digest(raw), purpose: purpose]
|
||||
t if t && t.used_at.nil? && t.expires_at > Time.now && t.user&.active
|
||||
end
|
||||
|
||||
def use!
|
||||
update(used_at: Time.now.utc)
|
||||
end
|
||||
end
|
||||
|
|
|
|||
221
lib/users_admin.rb
Normal file
221
lib/users_admin.rb
Normal file
|
|
@ -0,0 +1,221 @@
|
|||
# /admin/users (manage accounts), /admin/audit, and the public one-time
|
||||
# invite / password-reset pages. Registered into AsxpioWeb after AdminAuth.
|
||||
module UsersAdmin
|
||||
module Helpers
|
||||
# Permission flags from the form. The acting user can only change flags
|
||||
# they hold themselves (no escalation); any other flag keeps the target's
|
||||
# current value. Ticking delete implies read.
|
||||
def permission_params(target = nil)
|
||||
User::AREAS.to_h do |area|
|
||||
flags = User::PERMS.select do |f|
|
||||
if current_user.can?(area, f) then params.dig('perm', area, f) == '1'
|
||||
else target&.can?(area, f) || false
|
||||
end
|
||||
end
|
||||
flags |= ['read'] if flags.include?('delete')
|
||||
[area, flags]
|
||||
end
|
||||
end
|
||||
|
||||
def save_permissions!(user, perms)
|
||||
UserPermission.where(user_id: user.id).delete
|
||||
perms.each do |area, flags|
|
||||
next if flags.empty?
|
||||
UserPermission.create(user_id: user.id, area: area, **flags.to_h { |f| [:"can_#{f}", true] })
|
||||
end
|
||||
end
|
||||
|
||||
def perm_summary(user)
|
||||
return 'superuser' if user.superuser
|
||||
user.permissions.map do |p|
|
||||
f = User::PERMS.select { |x| p[:"can_#{x}"] }.map { |x| x[0] }.join
|
||||
f.empty? ? nil : "#{p.area}: #{f}"
|
||||
end.compact.join(' · ').then { |s| s.empty? ? 'no access' : s }
|
||||
end
|
||||
|
||||
# Email the link if possible; the acting admin also sees it once, so an
|
||||
# account without email (or a failed send) can still be onboarded.
|
||||
def send_account_link(user, kind)
|
||||
raw = UserToken.issue!(user, kind)
|
||||
url = "#{request.base_url}/admin/#{kind}/#{raw}"
|
||||
sent = false
|
||||
if user.email
|
||||
begin
|
||||
Mailer.account_link(to: user.email, username: user.username, url: url, kind: kind)
|
||||
sent = true
|
||||
rescue StandardError => e
|
||||
$logger.error("users: #{kind} mail to #{user.email} failed: #{e.class}: #{e.message}")
|
||||
end
|
||||
end
|
||||
session[:users_link] = { 'url' => url, 'sent' => sent, 'to' => user.email, 'kind' => kind }
|
||||
end
|
||||
|
||||
def manageable!(user)
|
||||
halt 403, 'Only superusers can change superuser accounts.' if user.superuser && !current_user.superuser
|
||||
end
|
||||
|
||||
def set_password_page(purpose)
|
||||
@token = UserToken.find_valid(params[:token], purpose) or halt 404, 'This link is invalid or has expired.'
|
||||
@purpose = purpose
|
||||
@page_title = purpose == 'invite' ? 'Set your password' : 'Reset password'
|
||||
@noindex = true
|
||||
end
|
||||
end
|
||||
|
||||
def self.registered(app)
|
||||
app.helpers Helpers
|
||||
|
||||
app.get '/admin/users' do
|
||||
@page_title = 'Users · admin'
|
||||
@noindex = true
|
||||
@users = User.order(:username).eager(:permissions).all
|
||||
@flash = session.delete(:users_flash)
|
||||
@link = session.delete(:users_link)
|
||||
erb :'admin/users/index'
|
||||
end
|
||||
|
||||
app.get '/admin/users/new' do
|
||||
@user = User.new
|
||||
@page_title = 'New user · admin'
|
||||
@noindex = true
|
||||
erb :'admin/users/form'
|
||||
end
|
||||
|
||||
app.post '/admin/users' do
|
||||
@user = User.new(username: params[:username].to_s.strip.downcase, name: params[:name].to_s.strip,
|
||||
email: params[:email].to_s.strip.downcase.then { |e| e.empty? ? nil : e })
|
||||
@user.superuser = params[:superuser] == '1' if current_user.superuser
|
||||
unless @user.valid? && !User[username: @user.username] && !(@user.email && User[email: @user.email])
|
||||
@error = @user.errors.full_messages.join('; ').then { |m| m.empty? ? 'Username or email already in use.' : m }
|
||||
@page_title = 'New user · admin'
|
||||
@noindex = true
|
||||
status 422
|
||||
return erb :'admin/users/form'
|
||||
end
|
||||
@user.save
|
||||
save_permissions!(@user, permission_params) unless @user.superuser
|
||||
send_account_link(@user, 'invite')
|
||||
audit!('user.create', @user.username, perm_summary(@user.refresh))
|
||||
redirect '/admin/users'
|
||||
end
|
||||
|
||||
app.get '/admin/users/:id' do
|
||||
@user = User[params[:id].to_i] or halt 404
|
||||
@page_title = "#{@user.username} · admin"
|
||||
@noindex = true
|
||||
@flash = session.delete(:users_flash)
|
||||
erb :'admin/users/form'
|
||||
end
|
||||
|
||||
app.post '/admin/users/:id' do
|
||||
user = User[params[:id].to_i] or halt 404
|
||||
manageable!(user)
|
||||
self_edit = user.id == current_user.id
|
||||
before = perm_summary(user)
|
||||
user.name = params[:name].to_s.strip
|
||||
user.email = params[:email].to_s.strip.downcase.then { |e| e.empty? ? nil : e }
|
||||
unless self_edit # you can't lock yourself out
|
||||
active = params[:active] == '1'
|
||||
user.session_version += 1 if user.active && !active
|
||||
user.active = active
|
||||
user.superuser = params[:superuser] == '1' if current_user.superuser
|
||||
end
|
||||
if !user.valid? || (user.email && User.exclude(id: user.id).where(email: user.email).any?)
|
||||
session[:users_flash] = user.errors.full_messages.join('; ').then { |m| m.empty? ? 'Email already in use.' : m }
|
||||
redirect "/admin/users/#{user.id}"
|
||||
end
|
||||
perms = permission_params(user) # read before saving changes
|
||||
user.save
|
||||
save_permissions!(user, perms) unless user.superuser
|
||||
audit!('user.update', user.username, "#{before} → #{perm_summary(user.refresh)}#{' (disabled)' unless user.active}")
|
||||
session[:users_flash] = 'Saved.'
|
||||
redirect "/admin/users/#{user.id}"
|
||||
end
|
||||
|
||||
app.post '/admin/users/:id/invite' do
|
||||
user = User[params[:id].to_i] or halt 404
|
||||
manageable!(user)
|
||||
kind = user.password_digest ? 'reset' : 'invite'
|
||||
send_account_link(user, kind)
|
||||
audit!("user.#{kind}_link", user.username)
|
||||
redirect '/admin/users'
|
||||
end
|
||||
|
||||
app.post '/admin/users/:id/delete' do
|
||||
user = User[params[:id].to_i] or halt 404
|
||||
manageable!(user)
|
||||
halt 422, "You can't delete yourself." if user.id == current_user.id
|
||||
if user.superuser && User.where(superuser: true, active: true).exclude(id: user.id).empty?
|
||||
halt 422, "Can't delete the last active superuser."
|
||||
end
|
||||
user.destroy
|
||||
audit!('user.delete', user.username)
|
||||
session[:users_flash] = "Deleted #{user.username}."
|
||||
redirect '/admin/users'
|
||||
end
|
||||
|
||||
app.get '/admin/audit' do
|
||||
@page_title = 'Audit log · admin'
|
||||
@noindex = true
|
||||
@entries = Audit.recent
|
||||
erb :'admin/audit'
|
||||
end
|
||||
|
||||
# --- public: invite / reset links -----------------------------------
|
||||
|
||||
%w[invite reset].each do |purpose|
|
||||
app.get "/admin/#{purpose}/:token" do
|
||||
set_password_page(purpose)
|
||||
erb :'admin/set_password'
|
||||
end
|
||||
|
||||
app.post "/admin/#{purpose}/:token" do
|
||||
set_password_page(purpose)
|
||||
@error =
|
||||
if params[:password].to_s.length < User::MIN_PASS then "Password needs at least #{User::MIN_PASS} characters."
|
||||
elsif params[:password] != params[:confirm] then 'Passwords do not match.'
|
||||
end
|
||||
if @error
|
||||
status 422
|
||||
return erb :'admin/set_password'
|
||||
end
|
||||
user = @token.user
|
||||
user.password = params[:password]
|
||||
user.must_change_password = false
|
||||
user.session_version += 1
|
||||
user.save
|
||||
@token.use!
|
||||
log_in!(user)
|
||||
audit!("user.#{purpose}_accepted", user.username)
|
||||
redirect '/admin'
|
||||
end
|
||||
end
|
||||
|
||||
app.get '/admin/reset' do
|
||||
@page_title = 'Reset password'
|
||||
@noindex = true
|
||||
erb :'admin/reset_request'
|
||||
end
|
||||
|
||||
# Same answer whether or not the account exists (no enumeration).
|
||||
app.post '/admin/reset' do
|
||||
@page_title = 'Reset password'
|
||||
@noindex = true
|
||||
if AdminAuth.login_limit.allow?(client_ip)
|
||||
q = params[:login].to_s.strip.downcase
|
||||
user = User.where(active: true).where(Sequel.|({ username: q }, { email: q })).first
|
||||
if user&.email && user.password_digest
|
||||
url = "#{request.base_url}/admin/reset/#{UserToken.issue!(user, 'reset')}"
|
||||
begin
|
||||
Mailer.account_link(to: user.email, username: user.username, url: url, kind: 'reset')
|
||||
rescue StandardError => e
|
||||
$logger.error("users: reset mail failed: #{e.class}: #{e.message}")
|
||||
end
|
||||
Audit.log(action: 'user.reset_requested', user: user, ip: client_ip)
|
||||
end
|
||||
end
|
||||
@sent = true
|
||||
erb :'admin/reset_request'
|
||||
end
|
||||
end
|
||||
end
|
||||
Loading…
Add table
Add a link
Reference in a new issue