Files
clinch/app/controllers/api_keys_controller.rb
Dan Milne cc93f72f0a Notify users out-of-band when security settings change
Previously only TOTP-enabled triggered an email. Every other
security-relevant change — password change, TOTP disable, passkey
add/remove, API key create/revoke, email address change, backup-code
regeneration — happened silently, so an attacker on a stolen session
could quietly drop 2FA or hijack the email with no signal to the
account holder.

Add SecurityMailer with one method per event. Each email carries the
request IP, user-agent, and timestamp so the user can spot unfamiliar
activity. Email-address changes notify both the old and new addresses
with directional language; the old-address copy explicitly warns that
whoever made the change can now receive password reset emails.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-02 23:52:12 +10:00

54 lines
1.4 KiB
Ruby

class ApiKeysController < ApplicationController
before_action :set_api_key, only: :destroy
def index
@api_keys = Current.session.user.api_keys.includes(:application).order(created_at: :desc)
end
def new
@api_key = ApiKey.new
@applications = forward_auth_apps_for_user
end
def create
@api_key = Current.session.user.api_keys.build(api_key_params)
if @api_key.save
SecurityMailer.api_key_created(Current.session.user, name: @api_key.name, **security_event_context).deliver_later
flash[:api_key_token] = @api_key.plaintext_token
redirect_to api_key_path(@api_key)
else
@applications = forward_auth_apps_for_user
render :new, status: :unprocessable_entity
end
end
def show
@api_key = Current.session.user.api_keys.find(params[:id])
@plaintext_token = flash[:api_key_token]
redirect_to api_keys_path unless @plaintext_token
end
def destroy
@api_key.revoke!
SecurityMailer.api_key_revoked(@api_key.user, name: @api_key.name, **security_event_context).deliver_later
redirect_to api_keys_path, notice: "API key revoked."
end
private
def set_api_key
@api_key = Current.session.user.api_keys.find(params[:id])
end
def api_key_params
params.require(:api_key).permit(:name, :application_id, :expires_at)
end
def forward_auth_apps_for_user
user = Current.session.user
Application.forward_auth.active.select { |app| app.user_allowed?(user) }
end
end