You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

41 lines
848 B

  1. # frozen_string_literal: true
  2. # == Schema Information
  3. #
  4. # Table name: system_keys
  5. #
  6. # id :bigint(8) not null, primary key
  7. # key :binary
  8. # created_at :datetime not null
  9. # updated_at :datetime not null
  10. #
  11. class SystemKey < ApplicationRecord
  12. ROTATION_PERIOD = 1.week.freeze
  13. before_validation :set_key
  14. scope :expired, ->(now = Time.now.utc) { where(arel_table[:created_at].lt(now - ROTATION_PERIOD * 3)) }
  15. class << self
  16. def current_key
  17. previous_key = order(id: :asc).last
  18. if previous_key && previous_key.created_at >= ROTATION_PERIOD.ago
  19. previous_key.key
  20. else
  21. create.key
  22. end
  23. end
  24. end
  25. private
  26. def set_key
  27. return if key.present?
  28. cipher = OpenSSL::Cipher.new('AES-256-GCM')
  29. cipher.encrypt
  30. self.key = cipher.random_key
  31. end
  32. end