Module: SchwabRb::Auth

Defined in:
lib/schwab_rb/auth/token.rb,
lib/schwab_rb/auth/auth_context.rb,
lib/schwab_rb/auth/token_manager.rb,
lib/schwab_rb/auth/init_client_easy.rb,
lib/schwab_rb/auth/init_client_login.rb,
lib/schwab_rb/auth/login_flow_server.rb,
lib/schwab_rb/auth/init_client_token_file.rb

Defined Under Namespace

Classes: AuthContext, BrowserLauncher, InvalidHostname, LoginFlowServer, OS, RedirectServerExitedError, RedirectTimeoutError, Token, TokenManager

Class Method Summary collapse

Class Method Details

.build_auth_context(api_key, callback_url, state: nil) ⇒ Object



199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
# File 'lib/schwab_rb/auth/init_client_login.rb', line 199

def self.build_auth_context(api_key, callback_url, state: nil)
  oauth = OAuth2::Client.new(
    api_key,
    nil,
    site: SchwabRb::Constants::SCHWAB_BASE_URL,
    authorize_url: "/v1/oauth/authorize",
    connection_opts: { ssl: { verify: false } }
  )

  auth_params = { redirect_uri: callback_url }
  auth_params[:state] = state if state
  authorization_url = oauth.auth_code.authorize_url(auth_params)

  AuthContext.new(callback_url, authorization_url, state)
end

.client_from_received_url(api_key, app_secret, auth_context, received_url, token_path, enforce_enums: true) ⇒ Object



215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
# File 'lib/schwab_rb/auth/init_client_login.rb', line 215

def self.client_from_received_url(
  api_key, app_secret, auth_context, received_url, token_path, enforce_enums: true
)
  oauth = OAuth2::Client.new(
    api_key,
    app_secret,
    site: SchwabRb::Constants::SCHWAB_BASE_URL,
    token_url: "/v1/oauth/token"
  )
  uri = URI.parse(received_url)
  params = URI.decode_www_form(uri.query).to_h
  authorization_code = params["code"]

  token = oauth.auth_code.get_token(authorization_code, redirect_uri: auth_context.callback_url)

   = SchwabRb::Auth::TokenManager.from_oauth2_token(
    token,
    Time.now.to_i,
    token_path: token_path
  )
  .to_file

  session = OAuth2::AccessToken.new(
    oauth,
    token.token,
    refresh_token: token.refresh_token,
    expires_at: token.expires_at
  )

  SchwabRb::Client.new(
    api_key,
    app_secret,
    session,
    token_manager: ,
    enforce_enums: enforce_enums
  )
end

.create_ssl_certificateObject



175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
# File 'lib/schwab_rb/auth/init_client_login.rb', line 175

def self.create_ssl_certificate
  key = OpenSSL::PKey::RSA.new(2048)
  cert = OpenSSL::X509::Certificate.new

  cert.subject = OpenSSL::X509::Name.parse("/CN=127.0.0.1")
  cert.issuer = cert.subject
  cert.public_key = key.public_key
  cert.not_before = Time.now
  cert.not_after = Time.now + (60 * 60 * 24) # 1 day
  cert.serial = 0x0
  cert.version = 2
  cert.sign(key, OpenSSL::Digest.new("SHA256"))

  cert_file = Tempfile.new("cert.pem")
  cert_file.write(cert.to_pem)
  cert_file.close

  key_file = Tempfile.new("key.pem")
  key_file.write(key.to_pem)
  key_file.close

  [cert_file, key_file]
end

.init_client_easy(api_key, app_secret, callback_url, token_path, asyncio: false, enforce_enums: false, callback_timeout: 300.0, interactive: true, requested_browser: nil) ⇒ Object



10
11
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
46
47
# File 'lib/schwab_rb/auth/init_client_easy.rb', line 10

def self.init_client_easy(
  api_key,
  app_secret,
  callback_url,
  token_path,
  asyncio: false,
  enforce_enums: false,
  callback_timeout: 300.0,
  interactive: true,
  requested_browser: nil
)
  token_path = SchwabRb::PathSupport.expand_path(token_path)

  raise OAuth2::Error, "No token found" unless File.exist?(token_path)

  client = SchwabRb::Auth.init_client_token_file(
    api_key,
    app_secret,
    token_path,
    enforce_enums: enforce_enums
  )
  client.refresh! if client.session.expired?
  raise OAuth2::Error, "Token expired" if client.session.expired?

  client
rescue StandardError
  SchwabRb::Auth.(
    api_key,
    app_secret,
    callback_url,
    token_path,
    asyncio: asyncio,
    enforce_enums: enforce_enums,
    callback_timeout: callback_timeout,
    interactive: interactive,
    requested_browser: requested_browser
  )
end

.init_client_login(api_key, app_secret, callback_url, token_path, asyncio: false, enforce_enums: false, callback_timeout: 300.0, interactive: true, input: $stdin, requested_browser: nil) ⇒ Object

Raises:



64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
# File 'lib/schwab_rb/auth/init_client_login.rb', line 64

def self.(
  api_key,
  app_secret,
  callback_url,
  token_path,
  asyncio: false,
  enforce_enums: false,
  callback_timeout: 300.0,
  interactive: true,
  input: $stdin,
  requested_browser: nil
)
  token_path = SchwabRb::PathSupport.expand_path(token_path)

  callback_timeout = if !callback_timeout
                       0
  elsif callback_timeout.negative?
    raise ArgumentError, "callback_timeout must be non-negative"
  else
    callback_timeout
                     end

  parsed = URI.parse(callback_url)
  raise InvalidHostname, parsed.host unless parsed.host == "127.0.0.1"

  callback_port = parsed.port || 4567
  callback_path = parsed.path.empty? ? "/" : parsed.path

  cert_file, key_file = create_ssl_certificate

  SchwabRb::Auth::LoginFlowServer.run_in_thread(
    callback_port: callback_port,
    callback_path: callback_path,
    cert_file: cert_file,
    key_file: key_file
  )

  begin
    # NOTE: wait for server to start
    start_time = Time.now
    loop do
      begin
        uri = URI("https://127.0.0.1:#{callback_port}/status")
        http = Net::HTTP.new(uri.host, uri.port)
        http.use_ssl = true
        http.ca_file = cert_file.path

        http.set_debug_output($stdout)

        resp = http.get(uri.path)

        break if resp.is_a?(Net::HTTPSuccess)
      rescue Errno::ECONNREFUSED
        sleep 0.1
      end

      raise RedirectServerExitedError if Time.now - start_time > 5
    end

    auth_context = build_auth_context(api_key, callback_url)

    puts <<~MESSAGE
      ***********************************************************************
      Open this URL in your browser to log in:
      #{auth_context.authorization_url}
      ***********************************************************************
    MESSAGE

    if interactive
      puts "Press ENTER to open the browser..."
      input.gets
    end

    open_browser(requested_browser, auth_context.authorization_url)

    timeout_time = Time.now + callback_timeout
    received_url = nil

    while Time.now < timeout_time
      unless LoginFlowServer.queue.empty?
        received_url = LoginFlowServer.queue.pop
        break
      end
      sleep 0.1
    end

    raise RedirectTimeoutError unless received_url

    client_from_received_url(
      api_key,
      app_secret,
      auth_context,
      received_url,
      token_path
    )
  ensure
    LoginFlowServer.stop
  end
end

.init_client_token_file(api_key, app_secret, token_path, enforce_enums: true) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/schwab_rb/auth/init_client_token_file.rb', line 8

def self.init_client_token_file(api_key, app_secret, token_path, enforce_enums: true)
  token_path = SchwabRb::PathSupport.expand_path(token_path)

  oauth = OAuth2::Client.new(
    api_key,
    app_secret,
    site: SchwabRb::Constants::SCHWAB_BASE_URL,
    token_url: "/v1/oauth/token"
  )

   = SchwabRb::Auth::TokenManager.from_file(token_path)
  token = .token

  session = OAuth2::AccessToken.new(
    oauth,
    token.token,
    refresh_token: token.refresh_token,
    expires_at: token.expires_at
  )

  SchwabRb::Client.new(
    api_key,
    app_secret,
    session,
    token_manager: ,
    enforce_enums: enforce_enums
  )
end

.open_browser(browser, url, browser_launcher: BrowserLauncher) ⇒ Object



164
165
166
167
168
169
170
171
172
173
# File 'lib/schwab_rb/auth/init_client_login.rb', line 164

def self.open_browser(browser, url, browser_launcher: BrowserLauncher)
  open_args = Array(OS.open_cmd)
  if !browser.nil? && !browser.strip.empty? && OS.mac?
    open_args << "-a"
    open_args << browser.gsub(" ", "\\ ")
  end
  open_args << %("#{url}")
  
  browser_launcher.open open_args
end