2019-10-03 17:07:29 -04:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
|
|
|
class GrafanaIntegration < ApplicationRecord
|
|
|
|
belongs_to :project
|
|
|
|
|
|
|
|
attr_encrypted :token,
|
2022-08-01 11:11:13 -04:00
|
|
|
mode: :per_attribute_iv,
|
2019-10-03 17:07:29 -04:00
|
|
|
algorithm: 'aes-256-gcm',
|
2022-08-01 11:11:13 -04:00
|
|
|
key: Settings.attr_encrypted_db_key_base_32
|
2019-10-03 17:07:29 -04:00
|
|
|
|
2020-01-30 16:08:47 -05:00
|
|
|
before_validation :check_token_changes
|
|
|
|
|
2019-10-03 17:07:29 -04:00
|
|
|
validates :grafana_url,
|
|
|
|
length: { maximum: 1024 },
|
|
|
|
addressable_url: { enforce_sanitization: true, ascii_only: true }
|
|
|
|
|
2020-01-30 16:08:47 -05:00
|
|
|
validates :encrypted_token, :project, presence: true
|
2019-10-10 08:06:19 -04:00
|
|
|
|
2019-11-01 14:06:00 -04:00
|
|
|
validates :enabled, inclusion: { in: [true, false] }
|
|
|
|
|
2022-07-28 14:09:03 -04:00
|
|
|
before_validation :reset_token
|
|
|
|
|
2019-11-13 13:06:51 -05:00
|
|
|
scope :enabled, -> { where(enabled: true) }
|
|
|
|
|
2019-10-10 08:06:19 -04:00
|
|
|
def client
|
2019-11-01 14:06:00 -04:00
|
|
|
return unless enabled?
|
|
|
|
|
2019-10-10 08:06:19 -04:00
|
|
|
@client ||= ::Grafana::Client.new(api_url: grafana_url.chomp('/'), token: token)
|
|
|
|
end
|
2020-01-30 16:08:47 -05:00
|
|
|
|
|
|
|
def masked_token
|
|
|
|
mask(encrypted_token)
|
|
|
|
end
|
|
|
|
|
|
|
|
def masked_token_was
|
|
|
|
mask(encrypted_token_was)
|
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
2022-07-28 14:09:03 -04:00
|
|
|
def reset_token
|
|
|
|
if grafana_url_changed? && !encrypted_token_changed?
|
|
|
|
self.token = nil
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2020-01-30 16:08:47 -05:00
|
|
|
def token
|
|
|
|
decrypt(:token, encrypted_token)
|
|
|
|
end
|
|
|
|
|
|
|
|
def check_token_changes
|
|
|
|
return unless [encrypted_token_was, masked_token_was].include?(token)
|
|
|
|
|
|
|
|
clear_attribute_changes [:token, :encrypted_token, :encrypted_token_iv]
|
|
|
|
end
|
|
|
|
|
|
|
|
def mask(token)
|
|
|
|
token&.squish&.gsub(/./, '*')
|
|
|
|
end
|
2019-10-03 17:07:29 -04:00
|
|
|
end
|