guest@websec ~ % man r07-controller-callbacks
Controller Callback
controller callback ("filter") รันโค้ดก่อน หลัง หรือครอบ action นี่คือวิธีที่ base controller ของเราบังคับ login และตรวจสิทธิ์ในทุก endpoint โดยที่แต่ละ endpoint ไม่ต้องเขียนเอง
before_action ก่อนเริ่มทำงานทุก endpoint และเมื่อต้องการหยุดคำขอ ให้โยน App*Error ที่มีชื่อชัดเจนเพื่อให้ rescue_from แปลงเป็น JSON รูปแบบเดียวกันทั้งระบบcallback ที่มี
| callback | ทำงาน | ใช้ทำอะไร |
|---|---|---|
before_action | ก่อน action และหยุด chain ได้ | auth, ตรวจสิทธิ์, โหลด record |
after_action | หลัง action เฉพาะเมื่อจบปกติ | header ของ response, metrics |
around_action | ครอบ action ต้อง yield | จับเวลา, transaction, ตั้งค่า context |
skip_before_action | ลบ callback ที่สืบทอดมา | action สาธารณะใน controller ที่ต้อง login |
prepend_before_action | เพิ่มไว้หน้าสุดของ chain | ต้องทำงานก่อน callback ที่สืบทอดมา |
rescue_from | เมื่อมี exception หลุดออกจากส่วนใดข้างบน | แปลง exception เป็น JSON |
option ที่ใช้ได้กับทุกตัว: only:, except:, if:, unless: ลำดับคือ callback ของ class แม่ก่อน แล้วตามด้วยของ class ลูก ตามลำดับที่ประกาศ
chain ของ admin
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
การหยุด request ใน before_action ทำได้สองทาง: render (หรือ head) ซึ่งหยุด chain และส่ง response นั้นกลับ หรือ raise ซึ่งกระโดดไปที่ rescue_from ทันที เราเลือก raise class error ของเรา เพื่อให้ทุก error มีรูปแบบ JSON เดียวกัน
ข้ามเฉพาะบาง 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 คู่กับ only: เสมอ ถ้าเขียน skip_before_action :set_current_user เฉยๆ ทุก action ใน controller นั้น รวมถึง action ที่จะเพิ่มในอนาคต จะกลายเป็นสาธารณะโดยไม่มีใครสังเกตสิทธิ์มาจาก route
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", ...]เพิ่ม route แล้วสิทธิ์ "controller#action" ของมันจะมีขึ้นเองอัตโนมัติ check_permissions เทียบกับ string นี้ตรงๆ ตั้งชื่อ action ว่า my_* เมื่อ admin ทุกคนที่ login แล้วควรเข้าถึงได้ (เช่น โปรไฟล์ของตัวเอง)
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
endลองเช็กความเข้าใจ
Api::V1::Admin::AppController ประกาศ before_action :set_current_user และ RolesController ประกาศ before_action :set_client_application อันไหนทำงานก่อน?
callback ของ class แม่ทำงานก่อนตามลำดับที่ประกาศ ทำให้การค้นหา record ใช้ current_user ได้
before_action raise AppPermissionDenied แล้ว after_action ของ controller จะทำงานไหม?
ใช้ around_action กับ ensure ถ้ามีสิ่งที่ต้องทำเสมอ