Class: ApiApplication

Inherits:
ApplicationRecord show all
Defined in:
app/models/api_application.rb

Overview

Represents an application that can access the API using API keys.

Instance Method Summary collapse

Instance Method Details

#rotate_api_key!(expires_at: nil) ⇒ Hash

Rotates keys following the lifecycle:

grace_period -> expired  (no longer valid)
active       -> grace_period  (still valid, but caller is warned)
new key      -> active

Parameters:

  • expires_at (Time, nil) (defaults to: nil)

    the optional expiration time for the new key

Returns:

  • (Hash)

    a hash containing the new API key and its plaintext representation



16
17
18
19
20
21
22
23
# File 'app/models/api_application.rb', line 16

def rotate_api_key!(expires_at: nil)
  transaction do
    now = Time.current
    api_keys.grace_period.find_each { |key| key.update!(status: :expired, updated_at: now) }
    api_keys.active.find_each { |key| key.update!(status: :grace_period, updated_at: now) }
    issue_api_key!(expires_at: expires_at)
  end
end