webhook.rb 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. # frozen_string_literal: true
  2. # == Schema Information
  3. #
  4. # Table name: webhooks
  5. #
  6. # id :bigint(8) not null, primary key
  7. # url :string not null
  8. # events :string default([]), not null, is an Array
  9. # secret :string default(""), not null
  10. # enabled :boolean default(TRUE), not null
  11. # created_at :datetime not null
  12. # updated_at :datetime not null
  13. #
  14. class Webhook < ApplicationRecord
  15. EVENTS = %w(
  16. account.created
  17. report.created
  18. ).freeze
  19. scope :enabled, -> { where(enabled: true) }
  20. validates :url, presence: true, url: true
  21. validates :secret, presence: true, length: { minimum: 12 }
  22. validates :events, presence: true
  23. validate :validate_events
  24. before_validation :strip_events
  25. before_validation :generate_secret
  26. def rotate_secret!
  27. update!(secret: SecureRandom.hex(20))
  28. end
  29. def enable!
  30. update!(enabled: true)
  31. end
  32. def disable!
  33. update!(enabled: false)
  34. end
  35. private
  36. def validate_events
  37. errors.add(:events, :invalid) if events.any? { |e| !EVENTS.include?(e) }
  38. end
  39. def strip_events
  40. self.events = events.map { |str| str.strip.presence }.compact if events.present?
  41. end
  42. def generate_secret
  43. self.secret = SecureRandom.hex(20) if secret.blank?
  44. end
  45. end