Class: JwtAuthCognito::ApiKeyValidator

Inherits:
Object
  • Object
show all
Defined in:
lib/jwt_auth_cognito/api_key_validator.rb

Instance Method Summary collapse

Constructor Details

#initialize(config) ⇒ ApiKeyValidator

Returns a new instance of ApiKeyValidator.



7
8
9
10
# File 'lib/jwt_auth_cognito/api_key_validator.rb', line 7

def initialize(config)
  @config = config
  @redis_service = RedisService.new(config)
end

Instance Method Details

#can_access_app?(key_data, app_id) ⇒ Boolean

Returns:

  • (Boolean)


59
60
61
62
63
64
65
66
# File 'lib/jwt_auth_cognito/api_key_validator.rb', line 59

def can_access_app?(key_data, app_id)
  # System API keys can access any app
  return true if key_data[:scope] == 'system'

  # App API keys can only access their specific app
  context_app_id = key_data[:app_id] || key_data[:metadata]&.dig('appId')
  context_app_id == app_id
end

#client_api_key?(key_data) ⇒ Boolean

Returns:

  • (Boolean)


55
56
57
# File 'lib/jwt_auth_cognito/api_key_validator.rb', line 55

def client_api_key?(key_data)
  key_data[:scope] == 'client'
end

#has_permission?(key_data, permission) ⇒ Boolean

Returns:

  • (Boolean)


47
48
49
# File 'lib/jwt_auth_cognito/api_key_validator.rb', line 47

def has_permission?(key_data, permission)
  key_data[:permissions]&.include?(permission) || false
end

#system_api_key?(key_data) ⇒ Boolean

Returns:

  • (Boolean)


51
52
53
# File 'lib/jwt_auth_cognito/api_key_validator.rb', line 51

def system_api_key?(key_data)
  key_data[:scope] == 'system'
end

#validate_api_key(api_key) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/jwt_auth_cognito/api_key_validator.rb', line 12

def validate_api_key(api_key)
  # Validate basic format (64 hex characters)
  return { valid: false, error: 'Invalid API key format' } unless api_key&.match?(/\A[a-fA-F0-9]{64}\z/)

  begin
    key_data = @redis_service.get("api-keys:#{api_key}")
    return { valid: false, error: 'API key not found' } unless key_data

    parsed = JSON.parse(key_data)

    # Verify it's active
    return { valid: false, error: 'API key is inactive' } unless parsed['isActive']

    # Update last used (fire and forget for performance)
    update_last_used(api_key, parsed)

    {
      valid: true,
      key_data: {
        name: parsed['name'],
        permissions: parsed['permissions'],
        app_id: parsed['appId'],
        scope: parsed['scope'],
        created_at: parsed['createdAt'],
        last_used: parsed['lastUsed'],
        is_active: parsed['isActive'],
        metadata: parsed['metadata'] || {}
      }
    }
  rescue StandardError => e
    puts "Error validating API key: #{e.message}"
    { valid: false, error: 'API key validation failed' }
  end
end