guest@websec: ~/websec/r04-models/th — zsh — 100×40 เขียนโดย SaKKo YouTube ENTH

guest@websec ~ % man r04-models

Model และ ApplicationRecord

model คือ class Ruby สำหรับหนึ่งตาราง มันเป็นเจ้าของกฎของข้อมูลตัวเอง: อะไรถูกต้อง record เชื่อมโยงกันอย่างไร อยู่ในสถานะไหนได้บ้าง และแสดง JSON แบบไหนให้ผู้ใช้แต่ละกลุ่ม

Model หนึ่งคลาสดูแลกฎของตารางเดียวครบจบในตัว ทั้งความสัมพันธ์, validation, scope, สถานะ AASM และรูปแบบ JSON แยกตามผู้รับ (as_admin_json) ส่วนกลไกกลางอย่าง Soft Delete, ประวัติการแก้ไข และการซ่อนฟิลด์ความลับ ให้รวมไว้ที่ ApplicationRecord ที่เดียว

ApplicationRecord: แม่ของทุก model

Rails สร้าง ApplicationRecord มาให้ เพื่อให้มีที่เดียวสำหรับวางพฤติกรรมที่ทุก model ใช้ร่วมกัน มันเป็น abstract คือไม่มีตารางของตัวเอง เวอร์ชันของเราทำหลายอย่าง:

class ApplicationRecord < ActiveRecord::Base
  include SoftDeletable          # deleted_at, default_scope, soft_delete!, restore
  primary_abstract_class         # no table; the app's main DB connection

  has_paper_trail skip: [:authentication_token, :otp_secret]   # audit history

  # Ransack search: only columns that don't look like secrets
  def self.ransackable_attributes(auth_object = nil)
    column_names - column_names.select { |x| ["passw", "token", "encryp"].any? { |f| x.include?(f) } } + _ransackers.keys
  end

  def self.ransackable_associations(auth_object = nil)
    reflect_on_all_associations.map { |a| a.name.to_s }
  end

  # Last line of defence: never serialize secret-looking columns
  def as_json(options = {})
    except = attributes.keys.select { |key| ["_ip", "sign_in", "_token", "password", "remember", "otp", "locked_at"].any? { |y| key.include?(y) } }
    super(options).except(*except)
  end
end
บรรทัดทุก model ได้…
include SoftDeletablesoft delete แทนการลบจริง และซ่อนแถวที่ถูกลบโดยอัตโนมัติ
has_paper_trailประวัติ versions ของทุกการเปลี่ยนแปลง (ใครแก้ แก้อะไร) ยกเว้นคอลัมน์ลับ
ransackable_*ตัวกรองค้นหาที่ปลอดภัย: client กรองด้วย password_digest เพื่อเดาค่าไม่ได้
as_jsonคอลัมน์ token / password / OTP ถูกตัดออกจาก JSON เริ่มต้นทุกกรณี
พฤติกรรมที่ทุก model ใช้ร่วมกันให้ใส่ใน ApplicationRecord (หรือ concern ที่มัน include) ห้าม copy ไปวางในแต่ละ model ส่วนพฤติกรรมเฉพาะ model ให้อยู่ใน model นั้น

โครงสร้าง model ของเรา

ทุก model เรียงส่วนต่างๆ ในลำดับเดียวกัน คุณจะรู้เสมอว่าต้องหาตรงไหน:

# == Schema Information          <- 1. generated by annotaterb, never hand-edit
#  id          :uuid  not null, primary key
#  name        :text  not null
#  app_key     :text  not null
#  ...
class ClientApplication < ApplicationRecord
  has_many :roles                                # 2. associations
  has_many :permissions

  before_validation :generate_credentials, on: :create   # 3. callbacks

  validates :name, :app_key, :api_secret, presence: true # 4. validations
  validates :app_key, uniqueness: true

  def notify_webhook(event_name, payload = {})   # 5. public behaviour
    return if webhook_url.blank?
    ClientApplicationWebhookJob.perform_later(id, event_name, payload)
  end

  def as_admin_json                              # 6. JSON shapes per audience
    { id:, allowed_hosts:, app_key:, name:, created_at:, updated_at:, webhook_url: }
  end

  def as_admin_show_json                         #    the secret only on "show"
    as_admin_json.merge(api_secret:)
  end

  private                                        # 7. private helpers + soft-delete hooks

  def generate_credentials
    self.app_key ||= loop do
      token = SecureRandom.hex(16)
      break token unless self.class.exists?(app_key: token)
    end
    self.api_secret ||= SecureRandom.hex(32)
  end

  def cascade_soft_delete
    roles.not_deleted.find_each(&:soft_delete!)
  end

  def cascade_restore
    nil # nothing to cascade
  end
end

Association

class User < ApplicationRecord
  has_many :user_roles
  has_many :roles, through: :user_roles     # many-to-many via a join model
end

class UserRole < ApplicationRecord
  belongs_to :user                          # required by default: user must exist
  belongs_to :role
end

class Role < ApplicationRecord
  belongs_to :client_application
  has_many :user_roles
  has_many :users, through: :user_roles
end

เราใช้ join model จริง (UserRole) แทน has_and_belongs_to_many เพราะตัวความสัมพันธ์เองก็มีข้อมูล: status, timestamp, soft delete และ state machine ของตัวเอง

Validation

validates :name, presence: true, uniqueness: { scope: :client_application_id }
validates :status, presence: true, inclusion: { in: %w[active inactive] }
validates :username, presence: true, uniqueness: {
                       case_sensitive: false,
                       conditions: -> { not_deleted },          # ignore soft-deleted rows
                       message: "is already in use by an active account",
                     }
validate :validate_permissions_inclusion                        # custom method

private

def validate_permissions_inclusion
  return if permissions.blank?
  return unless client_application

  invalid = Array(permissions) - client_application.permissions.pluck(:name)
  errors.add(:permissions, "contains invalid permissions: #{invalid.join(", ")}") if invalid.any?
end
validation อย่างเดียวไม่ใช่ขอบเขตความปลอดภัย: update_columns, insert_all และ SQL ตรงๆ จะข้ามมันไป กฎสำคัญต้องมี constraint ในฐานข้อมูลรองรับ (null: false, unique index, foreign key)

Scope และ soft delete

module SoftDeletable
  extend ActiveSupport::Concern

  included do
    scope :not_deleted, -> { where(deleted_at: nil) }
    scope :deleted,     -> { where.not(deleted_at: nil) }
    scope :with_deleted, -> { unscope(where: :deleted_at) }

    default_scope { not_deleted }                 # every query hides deleted rows
    define_model_callbacks :soft_delete, :restore # custom callbacks (r05)
  end

  def soft_delete!                                # sets deleted_at, cascades
  def restore                                     # clears it, re-checks uniqueness
  def destroy                                     # raises: use soft_delete! or hard_destroy!
  def hard_destroy!                               # the only real DELETE
end

ทุก model ที่ include SoftDeletable ต้องเขียน cascade_soft_delete และ cascade_restore เพื่อบังคับให้ตัดสินใจทีละ model ว่าจะทำอะไรกับลูก: User soft delete user_roles ของตัวเอง ส่วน Department ไม่มีอะไรต้อง cascade และเขียนบอกไว้ว่า nil # nothing to cascade

รูปแบบ JSON อยู่ใน model

def as_admin_json(with_client_application: false, with_permissions: true)
  json = { id:, name:, created_at:, updated_at:, client_application_id:, description:, status:, deleted_at: }
  json[:permissions] = permissions if with_permissions
  json[:client_application] = client_application.as_admin_json if with_client_application
  json
end

def as_client_json(with_client_application: false, with_permissions: true)
  # same idea, for server-to-server clients
end
  • ระบุ field ชัดเจน: คอลัมน์ใหม่จะเป็นความลับจนกว่าคุณจะเพิ่มเข้าไปเอง api_secret ปรากฏเฉพาะใน as_admin_show_json ไม่เคยอยู่ในรายการ
  • หนึ่ง method ต่อผู้ใช้หนึ่งกลุ่ม: as_admin_json, as_client_json, as_admin_profile_json
  • flag with_*: สำหรับข้อมูลซ้อน endpoint ที่แสดงรายการจะได้ไม่โหลด association ที่ไม่ได้แสดง
  • { id:, name: } คือรูปย่อของ Ruby 3.1 สำหรับ { id: id, name: name }

class method กับ instance method

# class method: no record yet; find, create or sync one
def self.authenticate_and_sync!(username, password)
  entry = DirectoryService.authenticate!(username, password)    # service does the I/O
  sync_from_directory!(entry)
end

def self.sync_from_directory!(entry)
  user = find_or_initialize_by(username: entry[:username].downcase)
  user.assign_attributes(email: entry[:email], display_name: entry[:display_name])
  user.save!
  user
end

# instance method: acts on this record
def toggle_admin!
  update(is_admin: !is_admin?)
end
! ต่อท้ายหมายถึง "raise เมื่อล้มเหลว" (save!, sync_from_directory!) หรือ "เปลี่ยนสถานะ" (toggle_admin!, soft_delete!) ส่วน method ที่ลงท้ายด้วย ? คืนค่า boolean

State machine ด้วย AASM

class UserRole < ApplicationRecord
  include AASM

  aasm :status, timestamps: true, column: "status" do   # timestamps: sets active_at / inactive_at
    state :active, initial: true
    state :inactive

    event :activate do
      transitions from: :inactive, to: :active
    end

    event :inactivate do
      transitions from: :active, to: :inactive
    end
  end

  def admin_actionables              # tells the admin UI which buttons to show
    rows = []
    rows << "activate" if may_activate?
    rows << "inactivate" if may_inactivate?
    rows
  end
end

ลองเช็กความเข้าใจ

คุณเพิ่มคอลัมน์ salary ในตาราง users endpoint ไหนจะเปิดเผยค่านี้?

serializer ของเราระบุ field ชัดเจน คอลัมน์ใหม่จึงเป็นความลับโดยปริยาย

ทำไม Role.find(id) ถึง raise RecordNotFound สำหรับ role ที่ถูก soft delete?

ใช้ Role.with_deleted เมื่อจำเป็นต้องใช้แถวที่ถูกลบจริงๆ (เช่น เพื่อ restore)