Class: ApiKeys::ApiKey

Inherits:
ActiveRecord::Base
  • Object
show all
Defined in:
lib/api_keys/models/api_key.rb

Overview

The core ActiveRecord model representing an API key.

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#tokenObject (readonly)

Attributes & Serialization ==

Expose the plaintext token only immediately after creation



20
21
22
# File 'lib/api_keys/models/api_key.rb', line 20

def token
  @token
end

Instance Method Details

#active?Boolean

Returns:

  • (Boolean)


75
76
77
# File 'lib/api_keys/models/api_key.rb', line 75

def active?
  !revoked? && !expired?
end

#allows_scope?(required_scope) ⇒ Boolean

Basic scope check. Assumes scopes are stored as an array of strings. Returns true if the key has no specific scopes (allowing all) or includes the required scope.

Returns:

  • (Boolean)


81
82
83
84
85
86
87
# File 'lib/api_keys/models/api_key.rb', line 81

def allows_scope?(required_scope)
  # Type casting for scopes/metadata happens via the attribute definition in the engine.
  # Ensure the attribute is loaded/defined before using it.
  # Check if the attribute method exists before calling .blank? or .include?
  return true unless respond_to?(:scopes) # Guard clause if loaded before attribute definition
  scopes.blank? || scopes.include?(required_scope.to_s)
end

#expired?Boolean

Returns:

  • (Boolean)


71
72
73
# File 'lib/api_keys/models/api_key.rb', line 71

def expired?
  expires_at? && expires_at <= Time.current
end

#masked_tokenObject

Provides a masked version of the token for display (e.g., ak_live_••••rj4p) Requires the plaintext token to be available (only right after creation).



91
92
93
94
95
96
97
98
99
100
# File 'lib/api_keys/models/api_key.rb', line 91

def masked_token
  # return "[Token not available]" unless token # No longer needed
  # Show prefix, 4 bullets, last 4 chars of the random part
  # random_part = token.delete_prefix(prefix) # No longer needed
  # "#{prefix}••••#{random_part.last(4)}" # No longer needed

  # Use the stored prefix and last4 attributes
  return "[Invalid Key Data]" unless prefix.present? && last4.present?
  "#{prefix}••••#{last4}"
end

#revoke!Object

Instance Methods ==



63
64
65
# File 'lib/api_keys/models/api_key.rb', line 63

def revoke!
  update!(revoked_at: Time.current)
end

#revoked?Boolean

Returns:

  • (Boolean)


67
68
69
# File 'lib/api_keys/models/api_key.rb', line 67

def revoked?
  revoked_at.present?
end