guest@websec ~ % man r07-controller-callbacks
Controller Callbacks
Controller callbacks ("filters") run code before, after or around an action. They are how our base controllers enforce login and permissions on every endpoint without each endpoint asking.
before_action before any endpoint runs. Halt requests by raising a named App*Error so rescue_from renders one consistent JSON error envelope.The callbacks
| callback | runs | typical use |
|---|---|---|
before_action | before the action; can halt | auth, permissions, loading records |
after_action | after the action, only if it finished normally | response headers, metrics |
around_action | wraps the action; must yield | timing, transactions, setting context |
skip_before_action | removes an inherited callback | public actions in an authenticated controller |
prepend_before_action | adds to the front of the chain | must run before inherited ones |
rescue_from | when an exception escapes anything above | turn exceptions into JSON |
Options on all of them: only:, except:, if:, unless:. Order: parent class callbacks first, then the child’s, each in the order declared.
Our admin chain
class Api::V1::Admin::AppController < Api::V1::AppController before_action :verify_x_requested_with # 1. CSRF guard for cookie auth before_action :set_current_user # 2. who is calling? before_action :set_paper_trail_whodunnit # 3. audit: who changed it before_action :check_permissions # 4. may they call this action? def set_current_user(type = :bearer) @current_user = User.find_by_jwt(fetch_cookies(type), type) raise AppAuthenticationError.new("not logged in") if current_user.blank? raise AppAuthenticationError.new("user not admin") if !current_user.is_admin? update_cookies(type, current_user.jwt(type)) # sliding expiry end def check_permissions return if params[:action][0..2] == "my_" # my_* actions are always allowed controller_action = "#{params[:controller]}##{params[:action]}" return if controller_action.include?("api/v1/admin/sessions") raise AppPermissionDenied.new("You are not allowed to call #{controller_action}") if !current_user.permissions.include?(controller_action) end private def verify_x_requested_with return if %w[GET HEAD OPTIONS].include?(request.request_method) unless request.headers["X-Requested-With"] == "XMLHttpRequest" render json: { error: "Missing required client header" }, status: :forbidden # render halts end end end
Two ways to stop a request in a before_action: render (or head), which halts the chain and sends that response; or raise, which jumps straight to rescue_from. We prefer raising one of our error classes, so every error has the same JSON envelope.
Skipping for one action
class Api::V1::Admin::SessionsController < Api::V1::Admin::AppController skip_before_action :set_current_user, only: [:create, :destroy] skip_before_action :set_paper_trail_whodunnit, only: [:create, :destroy] def create # login: nobody is logged in yet ... end def me # still protected: needs current_user render json: { user: current_user.as_admin_profile_json } end def destroy # logout: try to find the user, but never fail set_current_user rescue nil current_user&.reset_authentication_token update_cookies(:bearer, "") render json: { success: true } end end
skip_before_action with only:. A bare skip_before_action :set_current_user silently makes every current and future action in that controller public.Permissions come from the routes
def self.all_admin_permissions
Rails.application.routes.routes
.map { |r| { path: r.path.spec.to_s, controller: r.defaults[:controller], action: r.defaults[:action] } }
.select { |x| x[:path].include?("/api/v1/admin") }
.group_by { |x| x[:controller] }
.transform_values { |v| v.map { |x| x[:action] }.uniq.reject { |a| a.include?("my_") } }
.except("api/v1/admin/sessions")
.flat_map { |controller, actions| actions.map { |a| "#{controller}##{a}" } }
end
# => ["api/v1/admin/client_applications#index", "api/v1/admin/roles#create", ...]Add a route and its "controller#action" permission exists automatically; check_permissions compares against exactly that string. Name actions my_* when every logged-in admin should reach them (their own profile, for example).
after_action / around_action
class Api::V1::Admin::ReportsController < Api::V1::Admin::AppController
around_action :log_duration, only: :export
after_action :no_store, only: :export
private
def log_duration
started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
yield # the action (and later filters) run here
ensure
Rails.logger.info("export took #{(Process.clock_gettime(Process::CLOCK_MONOTONIC) - started).round(3)}s")
end
def no_store
response.headers["Cache-Control"] = "no-store" # sensitive download: don't cache
end
endCheck yourself
Api::V1::Admin::AppController declares before_action :set_current_user. RolesController declares before_action :set_client_application. Which runs first?
Parent callbacks run first, in declaration order. That's why the record lookup can rely on current_user.
A before_action raises AppPermissionDenied. Does the controller's after_action run?
Use around_action with ensure if something must always happen.