Module: ApiKeys::Models::Concerns::HasApiKeys

Extended by:
ActiveSupport::Concern
Defined in:
lib/api_keys/models/concerns/has_api_keys.rb

Overview

Concern to add API key capabilities to an owner model (e.g., User, Organization). This module provides the ‘has_api_keys` class method when extended onto ActiveRecord::Base.

Defined Under Namespace

Modules: ClassMethods Classes: DslProvider

Instance Method Summary collapse

Instance Method Details

#create_api_key!(name: nil, scopes: nil, expires_at: nil, metadata: nil) ⇒ ApiKeys::ApiKey

Creates a new API key for this owner instance and returns the ApiKey instance. Raises ActiveRecord::RecordInvalid if creation fails.



108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
# File 'lib/api_keys/models/concerns/has_api_keys.rb', line 108

def create_api_key!(name: nil, scopes: nil, expires_at: nil, metadata: nil)
  # Fetch default scopes from this owner class's settings, falling back to global config.
  owner_settings = self.class.api_keys_settings
  default_scopes = owner_settings&.[](:default_scopes) || ApiKeys.configuration.default_scopes || []

  # Use provided scopes if given, otherwise use the calculated defaults.
  key_scopes = scopes.nil? ? default_scopes : Array(scopes)

  # Create the key using the association, letting AR handle owner_id/type.
  api_key = self.api_keys.create!(
    name: name,
    scopes: key_scopes,
    expires_at: expires_at,
    metadata:  || {} # Ensure metadata is at least an empty hash
    # prefix, token_digest, digest_algorithm are set by ApiKey callbacks
  )

  # Return the ApiKey instance itself.
  # The plaintext token is available via `api_key.token` immediately after this.
  api_key
end