Module: LcpRuby::ApiTokens::Verifier

Defined in:
lib/lcp_ruby/api_tokens/verifier.rb

Constant Summary collapse

DEBOUNCE_INTERVAL =
1.minute

Class Method Summary collapse

Class Method Details

.touch_last_used_at(token) ⇒ Object



31
32
33
34
35
# File 'lib/lcp_ruby/api_tokens/verifier.rb', line 31

def self.touch_last_used_at(token)
  return if token.last_used_at.present? && token.last_used_at > DEBOUNCE_INTERVAL.ago

  token.update_columns(last_used_at: Time.current)
end

.verify(plaintext) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/lcp_ruby/api_tokens/verifier.rb', line 8

def self.verify(plaintext)
  return nil if plaintext.nil? || plaintext.empty?

  token_class = LcpRuby.registry.model_for("api_token")
  return nil unless token_class

  hash = TokenGenerator.hash(plaintext)
  token = token_class.find_by(token_hash: hash)
  return nil unless token

  return nil unless ActiveSupport::SecurityUtils.secure_compare(token.token_hash.to_s, hash)
  return nil if token.revoked_at.present?
  return nil if token.expires_at.present? && token.expires_at < Date.current

  touch_last_used_at(token)

  user = token.user
  return nil if user.nil?
  return nil if user.respond_to?(:active?) && !user.active?

  user
end