webhook.rb 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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.approved
  17. account.created
  18. report.created
  19. ).freeze
  20. scope :enabled, -> { where(enabled: true) }
  21. validates :url, presence: true, url: true
  22. validates :secret, presence: true, length: { minimum: 12 }
  23. validates :events, presence: true
  24. validate :validate_events
  25. before_validation :strip_events
  26. before_validation :generate_secret
  27. def rotate_secret!
  28. update!(secret: SecureRandom.hex(20))
  29. end
  30. def enable!
  31. update!(enabled: true)
  32. end
  33. def disable!
  34. update!(enabled: false)
  35. end
  36. private
  37. def validate_events
  38. errors.add(:events, :invalid) if events.any? { |e| !EVENTS.include?(e) }
  39. end
  40. def strip_events
  41. self.events = events.map { |str| str.strip.presence }.compact if events.present?
  42. end
  43. def generate_secret
  44. self.secret = SecureRandom.hex(20) if secret.blank?
  45. end
  46. end