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
|
|
@ -38,6 +38,8 @@ Banking details and registration number are deliberately not on the public page
|
|||
- `Rack::Protection::AuthenticityToken` for CSRF (uses session-stored token)
|
||||
- `AdminAuth` (`lib/admin_auth.rb`, a Sinatra extension): session login at `/admin/login` against the `users` table (`lib/user.rb`, scrypt via OpenSSL, no gem). Session holds user id + `session_version` (bump = logged out everywhere). `ADMIN_USER`/`ADMIN_PASSWORD` bootstrap the first superuser on an empty table and otherwise work only while no active superuser exists (recovery; it re-creates that superuser). Login is rate-limited per IP (`LOGIN_RATE_LIMIT`, default 10/15 min).
|
||||
- Permissions (`lib/admin_acl.rb`): areas `invoices`, `bingo`, `users` × independent flags read/write/delete in `user_permissions` (read + delete without write is valid); superusers bypass. GET → read (…/new, …/duplicate → write), POST …/delete|…/disable → delete, other POST → write. Unmapped /admin paths are superuser-only, and `test/admin_acl_test.rb` fails if a registered admin route isn't mapped — add new admin routes to `AdminACL::RULES`. Views hide forms via `can?(area, perm)`; the server check is the real gate.
|
||||
- Users UI (`lib/users_admin.rb`): `/admin/users` create/edit/disable/delete, permission grid (you can only grant flags you hold; flags you can't grant keep their value; only superusers touch superuser accounts; no self-lockout; last active superuser can't be deleted). New users get a one-time invite link (48 h) by email via `Mailer.account_link`, also shown once to the admin. `/admin/reset` emails a 1 h reset link (same answer for unknown accounts). Tokens are stored as SHA-256 only (`user_tokens`). `/admin/audit` lists `audit_log` (logins, user changes, bingo and invoice actions) — call `audit!(action, target, detail)` in new admin actions.
|
||||
- Timestamps: `Sequel.default_timezone = :utc` (lib/db.rb); always write `Time.now.utc`.
|
||||
- Honeypot field named `website` for spam
|
||||
- Static assets in `public/`; views in `views/`
|
||||
- Deploy: `Dockerfile` + `docker-compose.yml` (Traefik labels for asxp.io / www.asxp.io). Container joins two external Docker networks: `traefik` (ingress) and `storage` (Postgres + MinIO).
|
||||
|
|
|
|||
|
|
@ -24,6 +24,7 @@ require_relative 'lib/db'
|
|||
require_relative 'lib/admin_auth'
|
||||
require_relative 'lib/s3'
|
||||
require_relative 'lib/bingo_admin'
|
||||
require_relative 'lib/users_admin'
|
||||
|
||||
# Invoice model needs a live Sequel connection at class-definition time.
|
||||
if ENV['DATABASE_URL']
|
||||
|
|
@ -38,6 +39,7 @@ if ENV['DATABASE_URL']
|
|||
require_relative 'lib/bingo'
|
||||
Bingo.seed!
|
||||
require_relative 'lib/user'
|
||||
require_relative 'lib/audit'
|
||||
User.bootstrap!(ENV['ADMIN_USER'], ENV['ADMIN_PASSWORD'])
|
||||
else
|
||||
$logger.warn('DATABASE_URL not set — invoicing disabled')
|
||||
|
|
@ -67,6 +69,7 @@ class AsxpioWeb < Sinatra::Base
|
|||
use Rack::Protection::AuthenticityToken
|
||||
register AdminAuth
|
||||
register BingoAdmin
|
||||
register UsersAdmin
|
||||
|
||||
Mailer.configure!
|
||||
|
||||
|
|
@ -288,6 +291,7 @@ class AsxpioWeb < Sinatra::Base
|
|||
retry
|
||||
end
|
||||
|
||||
audit!('invoice.create', invoice.number, "#{invoice.client_name}, #{invoice.currency} #{'%.2f' % invoice.total}")
|
||||
redirect "/admin/invoices/#{invoice.uuid}"
|
||||
end
|
||||
|
||||
|
|
@ -302,6 +306,7 @@ class AsxpioWeb < Sinatra::Base
|
|||
invoice = Invoice[uuid: params[:uuid]] or halt 404
|
||||
invoice.paid_at = invoice.paid? ? nil : Time.now.utc
|
||||
invoice.save_changes
|
||||
audit!(invoice.paid? ? 'invoice.paid' : 'invoice.unpaid', invoice.number)
|
||||
redirect "/admin/invoices/#{invoice.uuid}"
|
||||
end
|
||||
|
||||
|
|
|
|||
27
db/migrations/008_user_tokens_audit.rb
Normal file
27
db/migrations/008_user_tokens_audit.rb
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
Sequel.migration do
|
||||
change do
|
||||
# One-time invite / password-reset links. Only a SHA-256 of the token
|
||||
# is stored; the raw token exists in the email and the URL.
|
||||
create_table(:user_tokens) do
|
||||
primary_key :id
|
||||
foreign_key :user_id, :users, null: false, on_delete: :cascade
|
||||
String :purpose, null: false # invite | reset
|
||||
String :token_digest, null: false, unique: true
|
||||
DateTime :expires_at, null: false
|
||||
DateTime :used_at
|
||||
DateTime :created_at, null: false
|
||||
end
|
||||
|
||||
create_table(:audit_log) do
|
||||
primary_key :id
|
||||
foreign_key :user_id, :users, on_delete: :set_null
|
||||
String :username # kept after the user is deleted
|
||||
String :action, null: false
|
||||
String :target
|
||||
String :detail, text: true
|
||||
String :ip
|
||||
DateTime :created_at, null: false
|
||||
index :created_at
|
||||
end
|
||||
end
|
||||
end
|
||||
|
|
@ -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
|
||||
164
test/users_admin_test.rb
Normal file
164
test/users_admin_test.rb
Normal file
|
|
@ -0,0 +1,164 @@
|
|||
require_relative 'test_helper'
|
||||
|
||||
class UsersAdminTest < Minitest::Test
|
||||
include Rack::Test::Methods
|
||||
include AdminLogin
|
||||
|
||||
def app
|
||||
AsxpioWeb
|
||||
end
|
||||
|
||||
def setup
|
||||
skip 'TEST_DATABASE_URL not set' unless TestDb.available?
|
||||
TestDb.clean_users!
|
||||
DB.connection[:audit_log].delete
|
||||
Mail::TestMailer.deliveries.clear
|
||||
end
|
||||
|
||||
def token(path = '/admin/users')
|
||||
get path
|
||||
last_response.body[/name="authenticity_token" value="([^"]+)"/, 1]
|
||||
end
|
||||
|
||||
def create_user(params)
|
||||
post '/admin/users', { authenticity_token: token('/admin/users/new') }.merge(params)
|
||||
end
|
||||
|
||||
def invite_url
|
||||
Mail::TestMailer.deliveries.last.body.to_s[%r{https?://\S+/admin/invite/\S+}]
|
||||
end
|
||||
|
||||
def test_superuser_creates_user_and_invite_is_emailed_and_shown
|
||||
admin_login!
|
||||
create_user(username: 'carol', email: 'carol@example.com', perm: { 'bingo' => { 'read' => '1', 'delete' => '1' } })
|
||||
assert_equal 302, last_response.status
|
||||
carol = User[username: 'carol']
|
||||
assert carol.can?('bingo', 'read')
|
||||
assert carol.can?('bingo', 'delete')
|
||||
refute carol.can?('bingo', 'write')
|
||||
assert_nil carol.password_digest
|
||||
assert_equal ['carol@example.com'], Mail::TestMailer.deliveries.last.to
|
||||
get '/admin/users'
|
||||
assert_includes last_response.body, 'emailed to carol@example.com'
|
||||
assert_includes last_response.body, '/admin/invite/'
|
||||
get '/admin/users'
|
||||
refute_includes last_response.body, '/admin/invite/' # shown once
|
||||
end
|
||||
|
||||
def test_delete_implies_read
|
||||
admin_login!
|
||||
create_user(username: 'dave', perm: { 'bingo' => { 'delete' => '1' } })
|
||||
assert User[username: 'dave'].can?('bingo', 'read')
|
||||
end
|
||||
|
||||
def test_invite_accept_sets_password_and_is_single_use
|
||||
admin_login!
|
||||
create_user(username: 'carol', email: 'carol@example.com')
|
||||
path = URI(invite_url).path
|
||||
clear_cookies
|
||||
get path
|
||||
assert last_response.ok?
|
||||
assert_includes last_response.body, 'carol'
|
||||
tok = last_response.body[/name="authenticity_token" value="([^"]+)"/, 1]
|
||||
post path, { authenticity_token: tok, password: 'short', confirm: 'short' }
|
||||
assert_equal 422, last_response.status
|
||||
post path, { authenticity_token: tok, password: 'carol-password-1', confirm: 'carol-password-1' }
|
||||
assert_equal 302, last_response.status
|
||||
assert User[username: 'carol'].authenticate('carol-password-1')
|
||||
get '/admin'
|
||||
assert last_response.ok? # logged in
|
||||
clear_cookies
|
||||
get path
|
||||
assert_equal 404, last_response.status # used
|
||||
end
|
||||
|
||||
def test_expired_invite_rejected
|
||||
u = User.create(username: 'erin')
|
||||
raw = UserToken.issue!(u, 'invite')
|
||||
UserToken.where(user_id: u.id).update(expires_at: Time.now.utc - 1)
|
||||
get "/admin/invite/#{raw}"
|
||||
assert_equal 404, last_response.status
|
||||
end
|
||||
|
||||
def test_reset_request_same_answer_and_mails_only_real_accounts
|
||||
User.create(username: 'frank', email: 'frank@example.com', password: 'frank-password-1')
|
||||
get '/admin/reset'
|
||||
tok = last_response.body[/name="authenticity_token" value="([^"]+)"/, 1]
|
||||
post '/admin/reset', { authenticity_token: tok, login: 'nobody' }
|
||||
nobody = last_response.body
|
||||
post '/admin/reset', { authenticity_token: tok, login: 'frank@example.com' }
|
||||
assert_equal nobody.scan(/reset link is on its way/), last_response.body.scan(/reset link is on its way/)
|
||||
assert_equal 1, Mail::TestMailer.deliveries.size
|
||||
url = Mail::TestMailer.deliveries.last.body.to_s[%r{https?://\S+/admin/reset/\S+}]
|
||||
get URI(url).path
|
||||
assert last_response.ok?, "#{url.inspect} -> #{last_response.status} #{last_response.body[0, 200]}"
|
||||
end
|
||||
|
||||
def test_no_escalation_by_user_manager
|
||||
boss = User.create(username: 'manager', password: 'manager-pass-1')
|
||||
UserPermission.create(user_id: boss.id, area: 'users', can_read: true, can_write: true)
|
||||
UserPermission.create(user_id: boss.id, area: 'bingo', can_read: true)
|
||||
target = User.create(username: 'grace', password: 'grace-password-1')
|
||||
UserPermission.create(user_id: target.id, area: 'invoices', can_read: true)
|
||||
admin_login!(username: 'manager', password: 'manager-pass-1')
|
||||
|
||||
create_user(username: 'henry', superuser: '1', perm: { 'invoices' => { 'write' => '1' }, 'bingo' => { 'read' => '1' } })
|
||||
henry = User[username: 'henry']
|
||||
refute henry.superuser
|
||||
refute henry.can?('invoices', 'write') # manager lacks it
|
||||
assert henry.can?('bingo', 'read')
|
||||
|
||||
post "/admin/users/#{target.id}", { authenticity_token: token, name: 'G', active: '1', perm: { 'bingo' => { 'read' => '1' } } }
|
||||
target.refresh
|
||||
assert target.can?('invoices', 'read') # kept: manager can't touch it
|
||||
assert target.can?('bingo', 'read')
|
||||
|
||||
root = User.create(username: 'root', superuser: true, password: 'root-password-11')
|
||||
post "/admin/users/#{root.id}", { authenticity_token: token, name: 'x', active: '' }
|
||||
assert_equal 403, last_response.status
|
||||
end
|
||||
|
||||
def test_cannot_delete_self_or_last_superuser
|
||||
admin_login!
|
||||
me = User[username: ENV['ADMIN_USER']]
|
||||
post "/admin/users/#{me.id}/delete", { authenticity_token: token }
|
||||
assert_equal 422, last_response.status
|
||||
other = User.create(username: 'other', superuser: true, password: 'other-password-1')
|
||||
post "/admin/users/#{other.id}/delete", { authenticity_token: token }
|
||||
assert_equal 302, last_response.status
|
||||
assert_nil User[other.id]
|
||||
end
|
||||
|
||||
def test_disabling_logs_user_out
|
||||
admin_login!
|
||||
u = User.create(username: 'ivan', password: 'ivan-password-12')
|
||||
v = u.session_version
|
||||
post "/admin/users/#{u.id}", { authenticity_token: token, name: '', email: '' } # active unticked
|
||||
u.refresh
|
||||
refute u.active
|
||||
assert_equal v + 1, u.session_version
|
||||
end
|
||||
|
||||
def test_audit_log_records_and_lists
|
||||
admin_login!
|
||||
create_user(username: 'judy')
|
||||
actions = DB.connection[:audit_log].select_map(:action)
|
||||
assert_includes actions, 'auth.login'
|
||||
assert_includes actions, 'user.create'
|
||||
get '/admin/audit'
|
||||
assert last_response.ok?
|
||||
assert_includes last_response.body, 'user.create'
|
||||
assert_includes last_response.body, 'judy'
|
||||
end
|
||||
|
||||
def test_users_read_only_cannot_create
|
||||
u = User.create(username: 'viewer', password: 'viewer-password1')
|
||||
UserPermission.create(user_id: u.id, area: 'users', can_read: true)
|
||||
admin_login!(username: 'viewer', password: 'viewer-password1')
|
||||
get '/admin/users'
|
||||
assert last_response.ok?
|
||||
refute_includes last_response.body, '+ New user'
|
||||
get '/admin/users/new'
|
||||
assert_equal 403, last_response.status
|
||||
end
|
||||
end
|
||||
23
views/admin/audit.erb
Normal file
23
views/admin/audit.erb
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
<%== erb :'admin/_nav', layout: false %>
|
||||
<div class="header">
|
||||
<h1>Audit log</h1>
|
||||
<p class="tagline"><a href="/admin/users">← users</a> · last <%= @entries.size %> entries</p>
|
||||
</div>
|
||||
|
||||
<section class="section">
|
||||
<table class="invoice-list">
|
||||
<thead><tr><th>Time (UTC)</th><th>User</th><th>Action</th><th>Target</th><th>Detail</th><th>IP</th></tr></thead>
|
||||
<tbody>
|
||||
<% @entries.each do |e| %>
|
||||
<tr>
|
||||
<td class="mono"><%= e[:created_at].strftime('%Y-%m-%d %H:%M') %></td>
|
||||
<td><%= e[:username] || '—' %></td>
|
||||
<td class="mono"><%= e[:action] %></td>
|
||||
<td><%= e[:target] %></td>
|
||||
<td class="optional"><%= e[:detail] %></td>
|
||||
<td class="mono optional"><%= e[:ip] %></td>
|
||||
</tr>
|
||||
<% end %>
|
||||
</tbody>
|
||||
</table>
|
||||
</section>
|
||||
|
|
@ -12,4 +12,5 @@
|
|||
<div class="field"><label for="password">Password</label><input type="password" id="password" name="password" autocomplete="current-password" required /></div>
|
||||
<button type="submit" class="download-button">Log in</button>
|
||||
</form>
|
||||
<p class="optional" style="text-align: center"><a href="/admin/reset">Forgot password?</a></p>
|
||||
</section>
|
||||
|
|
|
|||
16
views/admin/reset_request.erb
Normal file
16
views/admin/reset_request.erb
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
<div class="header">
|
||||
<h1>Reset password</h1>
|
||||
<p class="tagline"><a href="/admin/login">← log in</a></p>
|
||||
</div>
|
||||
|
||||
<section class="section">
|
||||
<% if @sent %>
|
||||
<p>If an account with an email address matches, a reset link is on its way. It works once and expires in 1 hour.</p>
|
||||
<% else %>
|
||||
<form class="invoice-form auth-form" method="post" action="/admin/reset">
|
||||
<input type="hidden" name="authenticity_token" value="<%= csrf_token %>" />
|
||||
<div class="field"><label for="login">Username or email</label><input type="text" id="login" name="login" autocomplete="username" autocapitalize="none" required autofocus /></div>
|
||||
<button type="submit" class="download-button">Send reset link</button>
|
||||
</form>
|
||||
<% end %>
|
||||
</section>
|
||||
15
views/admin/set_password.erb
Normal file
15
views/admin/set_password.erb
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
<div class="header">
|
||||
<h1><%= @purpose == 'invite' ? 'Welcome' : 'Reset password' %></h1>
|
||||
<p class="tagline">Set a password for <b><%= @token.user.username %></b></p>
|
||||
</div>
|
||||
|
||||
<section class="section">
|
||||
<% if @error %><div class="form-error-base"><div><%= @error %></div></div><% end %>
|
||||
<form class="invoice-form auth-form" method="post" action="/admin/<%= @purpose %>/<%= params[:token] %>">
|
||||
<input type="hidden" name="authenticity_token" value="<%= csrf_token %>" />
|
||||
<input type="text" name="username" value="<%= @token.user.username %>" autocomplete="username" hidden />
|
||||
<div class="field"><label for="password">Password <span class="optional">(at least <%= User::MIN_PASS %> characters)</span></label><input type="password" id="password" name="password" autocomplete="new-password" minlength="<%= User::MIN_PASS %>" required autofocus /></div>
|
||||
<div class="field"><label for="confirm">Repeat password</label><input type="password" id="confirm" name="confirm" autocomplete="new-password" required /></div>
|
||||
<button type="submit" class="download-button">Set password and log in</button>
|
||||
</form>
|
||||
</section>
|
||||
76
views/admin/users/form.erb
Normal file
76
views/admin/users/form.erb
Normal file
|
|
@ -0,0 +1,76 @@
|
|||
<% fresh = @user.new? %>
|
||||
<% editable = can?('users', 'write') && (!@user.superuser || current_user.superuser) %>
|
||||
<% self_edit = !fresh && @user.id == current_user.id %>
|
||||
<%== erb :'admin/_nav', layout: false %>
|
||||
<div class="header">
|
||||
<h1><%= fresh ? 'New user' : @user.username %></h1>
|
||||
<p class="tagline"><a href="/admin/users">← users</a></p>
|
||||
</div>
|
||||
|
||||
<% if @error || @flash %><div class="form-error-base"><div><%= @error || @flash %></div></div><% end %>
|
||||
|
||||
<section class="section">
|
||||
<form class="invoice-form" method="post" action="<%= fresh ? '/admin/users' : "/admin/users/#{@user.id}" %>" autocomplete="off">
|
||||
<input type="hidden" name="authenticity_token" value="<%= csrf_token %>" />
|
||||
<fieldset class="plain" <%= 'disabled' unless editable %>>
|
||||
<div class="invoice-grid">
|
||||
<div class="field"><label for="username">Username</label><input type="text" id="username" name="username" value="<%= @user.username %>" <%= fresh ? 'required pattern=[a-z0-9][a-z0-9_.@-]{1,63}' : 'disabled' %> /></div>
|
||||
<div class="field"><label for="name">Name <span class="optional">(optional)</span></label><input type="text" id="name" name="name" value="<%= @user.name %>" /></div>
|
||||
<div class="field"><label for="email">Email <span class="optional">(for invite and password reset)</span></label><input type="email" id="email" name="email" value="<%= @user.email %>" /></div>
|
||||
</div>
|
||||
|
||||
<% unless fresh %>
|
||||
<div class="field"><label><input type="checkbox" name="active" value="1" <%= 'checked' if @user.active %> <%= 'disabled' if self_edit %> /> Active <span class="optional">(unticking logs the user out)</span></label></div>
|
||||
<% end %>
|
||||
<% if current_user.superuser %>
|
||||
<div class="field"><label><input type="checkbox" name="superuser" value="1" id="superuser" <%= 'checked' if @user.superuser %> <%= 'disabled' if self_edit %> /> Superuser <span class="optional">(everything, incl. managing superusers; permissions below are ignored)</span></label></div>
|
||||
<% end %>
|
||||
|
||||
<h2>Permissions</h2>
|
||||
<table class="invoice-list perm-grid">
|
||||
<thead><tr><th>Area</th><% User::PERMS.each do |f| %><th><%= f %></th><% end %></tr></thead>
|
||||
<tbody>
|
||||
<% User::AREAS.each do |area| %>
|
||||
<tr>
|
||||
<td><%= area %></td>
|
||||
<% User::PERMS.each do |f| %>
|
||||
<td><input type="checkbox" name="perm[<%= area %>][<%= f %>]" value="1" data-area="<%= area %>" data-flag="<%= f %>"
|
||||
<%= 'checked' if !fresh && @user.can?(area, f) %> <%= 'disabled' unless current_user.can?(area, f) %> /></td>
|
||||
<% end %>
|
||||
</tr>
|
||||
<% end %>
|
||||
</tbody>
|
||||
</table>
|
||||
<p class="optional">You can only grant permissions you hold yourself. Delete implies read.</p>
|
||||
|
||||
<% if editable %><button type="submit" class="download-button"><%= fresh ? 'Create and send invite' : 'Save' %></button><% end %>
|
||||
</fieldset>
|
||||
</form>
|
||||
</section>
|
||||
|
||||
<% if !fresh && editable %>
|
||||
<section class="section">
|
||||
<form method="post" action="/admin/users/<%= @user.id %>/invite">
|
||||
<input type="hidden" name="authenticity_token" value="<%= csrf_token %>" />
|
||||
<button type="submit" class="link-button"><%= @user.password_digest ? '✉ Send password reset link' : '✉ Resend invite' %></button>
|
||||
</form>
|
||||
</section>
|
||||
<% end %>
|
||||
|
||||
<% if !fresh && !self_edit && can?('users', 'delete') && (!@user.superuser || current_user.superuser) %>
|
||||
<section class="section">
|
||||
<h2>Danger zone</h2>
|
||||
<form method="post" action="/admin/users/<%= @user.id %>/delete" onsubmit="return confirm('Delete this user? This cannot be undone.')">
|
||||
<input type="hidden" name="authenticity_token" value="<%= csrf_token %>" />
|
||||
<button type="submit" class="link-button">delete this user</button>
|
||||
</form>
|
||||
</section>
|
||||
<% end %>
|
||||
|
||||
<script>
|
||||
// Delete implies read: keep the read box ticked when delete is.
|
||||
document.querySelectorAll('[data-flag="delete"]').forEach(d => d.addEventListener('change', () => {
|
||||
const r = document.querySelector(`[data-area="${d.dataset.area}"][data-flag="read"]`);
|
||||
if (d.checked && r && !r.disabled) r.checked = true;
|
||||
}));
|
||||
</script>
|
||||
37
views/admin/users/index.erb
Normal file
37
views/admin/users/index.erb
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
<%== erb :'admin/_nav', layout: false %>
|
||||
<div class="header">
|
||||
<h1>Users</h1>
|
||||
<p class="tagline">
|
||||
<% if can?('users', 'write') %><a href="/admin/users/new">+ New user</a> · <% end %><a href="/admin/audit">audit log</a>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<% if @flash %><div class="form-error-base"><div><%= @flash %></div></div><% end %>
|
||||
<% if @link %>
|
||||
<section class="section">
|
||||
<p><%= @link['kind'] == 'invite' ? 'Invite' : 'Password reset' %> link<%= @link['sent'] ? " emailed to #{@link['to']}" : (@link['to'] ? " — email to #{@link['to']} FAILED, send it yourself" : ' (no email on file — send it yourself)') %>.
|
||||
Shown once; it works once and expires in <%= @link['kind'] == 'invite' ? '48 hours' : '1 hour' %>:</p>
|
||||
<p class="mono" style="word-break: break-all"><%= @link['url'] %></p>
|
||||
</section>
|
||||
<% end %>
|
||||
|
||||
<section class="section">
|
||||
<table class="invoice-list">
|
||||
<thead><tr><th>User</th><th>Access</th><th>Status</th><th>Last login</th><th></th></tr></thead>
|
||||
<tbody>
|
||||
<% @users.each do |u| %>
|
||||
<tr>
|
||||
<td><b><%= u.username %></b><% if u.name.to_s != '' %><br /><span class="optional"><%= u.name %></span><% end %><% if u.email %><br /><span class="optional"><%= u.email %></span><% end %></td>
|
||||
<td><%= perm_summary(u) %></td>
|
||||
<td>
|
||||
<% if !u.active %><span class="badge badge-pending">disabled</span>
|
||||
<% elsif !u.password_digest %><span class="badge badge-pending">invited</span>
|
||||
<% else %><span class="badge badge-paid">active</span><% end %>
|
||||
</td>
|
||||
<td class="mono"><%= u.last_login_at&.strftime('%Y-%m-%d %H:%M') || '—' %></td>
|
||||
<td class="actions"><a href="/admin/users/<%= u.id %>"><%= can?('users', 'write') ? 'edit' : 'view' %></a></td>
|
||||
</tr>
|
||||
<% end %>
|
||||
</tbody>
|
||||
</table>
|
||||
</section>
|
||||
Loading…
Add table
Add a link
Reference in a new issue