Class: Otto::Security::Authentication::Strategies::APIKeyStrategy

Inherits:
AuthStrategy
  • Object
show all
Defined in:
lib/otto/security/authentication/strategies/api_key_strategy.rb

Overview

API key authentication strategy

Instance Method Summary collapse

Constructor Details

#initialize(api_keys: [], header_name: 'X-API-Key', param_name: 'api_key') ⇒ APIKeyStrategy

Returns a new instance of APIKeyStrategy.



13
14
15
16
17
# File 'lib/otto/security/authentication/strategies/api_key_strategy.rb', line 13

def initialize(api_keys: [], header_name: 'X-API-Key', param_name: 'api_key')
  @api_keys = Array(api_keys)
  @header_name = header_name
  @param_name = param_name
end

Instance Method Details

#authenticate(env, _requirement) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/otto/security/authentication/strategies/api_key_strategy.rb', line 19

def authenticate(env, _requirement)
  # Try header first, then query parameter
  api_key = env["HTTP_#{@header_name.upcase.tr('-', '_')}"]

  if api_key.nil?
    request = Otto::Request.new(env)
    api_key = request.params[@param_name]
  end

  return failure('No API key provided') unless api_key

  if @api_keys.empty? || @api_keys.include?(api_key)
    # Create a simple user hash for API key authentication
    user_data = { api_key: api_key }
    success(user: user_data, api_key: api_key)
  else
    failure('Invalid API key')
  end
end