Class: RubyCoded::Strategies::OAuthStrategy

Inherits:
Base
  • Object
show all
Defined in:
lib/ruby_coded/strategies/oauth_strategy.rb

Overview

OAuth strategy for authentication with OAuth providers (OPENAI)

Instance Method Summary collapse

Methods inherited from Base

#initialize

Constructor Details

This class inherits a constructor from RubyCoded::Strategies::Base

Instance Method Details

#authenticateObject



18
19
20
21
22
23
24
25
26
27
# File 'lib/ruby_coded/strategies/oauth_strategy.rb', line 18

def authenticate
  pkce = Auth::PKCE.generate
  state = SecureRandom.hex(16)

  result = perform_oauth_flow(pkce[:challenge], state)
  validate_callback!(result, state)

  tokens = exchange_code(result[:code], pkce[:verifier])
  build_token_response(tokens)
end

#refresh(credentials) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/ruby_coded/strategies/oauth_strategy.rb', line 29

def refresh(credentials)
  response = Faraday.post(@provider.token_url, {
                            "grant_type" => "refresh_token",
                            "refresh_token" => credentials["refresh_token"],
                            "client_id" => @provider.client_id
                          })
  tokens = JSON.parse(response.body)

  {
    "auth_method" => "oauth",
    "access_token" => tokens["access_token"],
    "refresh_token" => tokens["refresh_token"] ||
      credentials["refresh_token"],
    "expires_at" => (Time.now + tokens["expires_in"].to_i).iso8601
  }
end

#validate(credentials) ⇒ Object



46
47
48
49
50
51
# File 'lib/ruby_coded/strategies/oauth_strategy.rb', line 46

def validate(credentials)
  return false unless credentials&.fetch("auth_method") ==
                      "oauth" && credentials&.fetch("access_token")

  Time.parse(credentials["expires_at"]) > Time.now
end