2019-05-02 17:17:27 -05:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2013-10-22 14:53:08 -05:00
|
|
|
class ApiKey < ActiveRecord::Base
|
|
|
|
belongs_to :user
|
2017-08-30 23:06:56 -05:00
|
|
|
belongs_to :created_by, class_name: 'User'
|
2013-10-22 14:53:08 -05:00
|
|
|
|
2019-11-05 08:10:23 -06:00
|
|
|
scope :active, -> { where("revoked_at IS NULL") }
|
|
|
|
scope :revoked, -> { where("revoked_at IS NOT NULL") }
|
|
|
|
|
2013-10-22 14:53:08 -05:00
|
|
|
validates_presence_of :key
|
|
|
|
|
2019-11-05 08:10:23 -06:00
|
|
|
after_initialize :generate_key
|
|
|
|
|
|
|
|
def generate_key
|
|
|
|
self.key ||= SecureRandom.hex(32)
|
2013-10-22 14:53:08 -05:00
|
|
|
end
|
|
|
|
|
2019-11-05 08:10:23 -06:00
|
|
|
def truncated_key
|
|
|
|
self.key[0..3]
|
|
|
|
end
|
|
|
|
|
|
|
|
def self.last_used_epoch
|
|
|
|
SiteSetting.api_key_last_used_epoch.presence
|
2013-10-22 14:53:08 -05:00
|
|
|
end
|
|
|
|
|
2019-11-05 08:10:23 -06:00
|
|
|
def self.revoke_unused_keys!
|
|
|
|
return if SiteSetting.revoke_api_keys_days == 0 # Never expire keys
|
|
|
|
to_revoke = active.where("GREATEST(last_used_at, created_at, updated_at, :epoch) < :threshold",
|
|
|
|
epoch: last_used_epoch,
|
|
|
|
threshold: SiteSetting.revoke_api_keys_days.days.ago
|
|
|
|
)
|
|
|
|
|
|
|
|
to_revoke.find_each do |api_key|
|
|
|
|
ApiKey.transaction do
|
|
|
|
api_key.update!(revoked_at: Time.zone.now)
|
|
|
|
|
|
|
|
StaffActionLogger.new(Discourse.system_user).log_api_key(
|
|
|
|
api_key,
|
|
|
|
UserHistory.actions[:api_key_update],
|
|
|
|
changes: api_key.saved_changes,
|
|
|
|
context: I18n.t("staff_action_logs.api_key.automatic_revoked", count: SiteSetting.revoke_api_keys_days))
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
2013-10-22 14:53:08 -05:00
|
|
|
end
|
2013-12-05 00:40:35 -06:00
|
|
|
|
|
|
|
# == Schema Information
|
|
|
|
#
|
|
|
|
# Table name: api_keys
|
|
|
|
#
|
|
|
|
# id :integer not null, primary key
|
|
|
|
# key :string(64) not null
|
|
|
|
# user_id :integer
|
|
|
|
# created_by_id :integer
|
2014-08-27 00:19:25 -05:00
|
|
|
# created_at :datetime not null
|
|
|
|
# updated_at :datetime not null
|
2014-11-19 21:53:15 -06:00
|
|
|
# allowed_ips :inet is an Array
|
2014-12-24 03:11:41 -06:00
|
|
|
# hidden :boolean default(FALSE), not null
|
2019-09-03 03:10:29 -05:00
|
|
|
# last_used_at :datetime
|
2019-11-19 04:20:14 -06:00
|
|
|
# revoked_at :datetime
|
|
|
|
# description :text
|
2013-12-05 00:40:35 -06:00
|
|
|
#
|
|
|
|
# Indexes
|
|
|
|
#
|
|
|
|
# index_api_keys_on_key (key)
|
2019-11-19 04:20:14 -06:00
|
|
|
# index_api_keys_on_user_id (user_id)
|
2013-12-05 00:40:35 -06:00
|
|
|
#
|