Class: RivetCms::ApiToken

Inherits:
ApplicationRecord show all
Includes:
OrganizationScoped
Defined in:
app/models/rivet_cms/api_token.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#plaintextObject (readonly)

Set only on the record returned by generate!; the secret is never stored.



19
20
21
# File 'app/models/rivet_cms/api_token.rb', line 19

def plaintext
  @plaintext
end

Class Method Details

.authenticate(raw) ⇒ Object

Global lookup — org is derived from the token, not scoped by the caller.



40
41
42
43
44
45
46
47
# File 'app/models/rivet_cms/api_token.rb', line 40

def self.authenticate(raw)
  return nil if raw.blank?

  token = find_by(token_digest: digest(raw))
  return nil if token.nil? || token.expired?

  token
end

.digest(raw) ⇒ Object



21
22
23
# File 'app/models/rivet_cms/api_token.rb', line 21

def self.digest(raw)
  Digest::SHA256.hexdigest(raw.to_s)
end

.generate!(name:, scope: :published, organization: RivetCms::Current.organization, expires_at: nil) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'app/models/rivet_cms/api_token.rb', line 25

def self.generate!(name:, scope: :published, organization: RivetCms::Current.organization, expires_at: nil)
  raw = SecureRandom.hex(32)
  token = create!(
    name: name,
    scope: scope,
    organization: organization,
    expires_at: expires_at,
    token_digest: digest(raw),
    token_last4: raw.last(4)
  )
  token.instance_variable_set(:@plaintext, raw)
  token
end

Instance Method Details

#expired?Boolean

Returns:

  • (Boolean)


49
50
51
# File 'app/models/rivet_cms/api_token.rb', line 49

def expired?
  expires_at.present? && expires_at.past?
end

#maskedObject



60
61
62
# File 'app/models/rivet_cms/api_token.rb', line 60

def masked
  "••••#{token_last4}"
end

#touch_used!Object

Throttled so the delivery API doesn't write to this row on every request.



54
55
56
57
58
# File 'app/models/rivet_cms/api_token.rb', line 54

def touch_used!
  return if last_used_at && last_used_at > 10.minutes.ago

  update_column(:last_used_at, Time.current)
end