class SC2Cli::Shared::Token
Attributes
expires[R]
region[R]
token[R]
Public Class Methods
new(configuration:, region: nil)
click to toggle source
# File lib/sc2cli/shared/token.rb, line 39 def initialize(configuration:, region: nil) @configuration = configuration @region = region || @configuration.region @@console.info("Finding token for region: #{@region.name} (#{@region.description})") @cache = Cache.new(configuration: @configuration, region: @region) begin from_cache rescue refresh end end
Public Instance Methods
check()
click to toggle source
# File lib/sc2cli/shared/token.rb, line 56 def check return valid(expires: @expires) end
refresh()
click to toggle source
# File lib/sc2cli/shared/token.rb, line 62 def refresh from_server @cache.update(token: @token, expires: @expires) end
Private Instance Methods
from_cache()
click to toggle source
# File lib/sc2cli/shared/token.rb, line 73 def from_cache raise "Cache 'token' or 'expires' objects are not set!" if @cache.token.nil? or @cache.expires.nil? raise "Cached token has already expired!" unless valid(expires: @cache.expires) @token = @cache.token @expires = @cache.expires end
from_server()
click to toggle source
# File lib/sc2cli/shared/token.rb, line 83 def from_server @@console.fatal("No client/secret in configuration and no usable token in cache!") unless @configuration.auth server = @region.oauth_server @@console.info("Refreshing token from: #{server}") uri = URI("https://#{server}/oauth/token") request = Net::HTTP::Post.new(uri) request.basic_auth(@configuration.client, @configuration.secret) request.set_form_data("grant_type" => "client_credentials") http = Net::HTTP.new(uri.hostname, uri.port) http.use_ssl = true response = http.request(request) @@console.fatal("Blizzard OAuth did not return status 200 for token reqest!") if response.code != "200" @@console.fatal("Response body from Blizzard OAuth is not permitted!") if not response.class.body_permitted? @@console.fatal("Response body from Blizzard OAuth is empty!") if response.body.nil? body = JSON.parse(response.body) @@console.fatal("Blizzard OAuth JSON response did not include an access token!") if not body.key?("access_token") @@console.fatal("Blizzard OAuth gave a blank access token!") if body["access_token"].empty? @@console.fatal("Blizzard OAuth JSON response did not include an expiry time!") if not body.key?("expires_in") token = body["access_token"] expires_in = body["expires_in"] expires = Time.now + expires_in @@console.fatal("Token received from Blizzard appears to have already expired!") unless valid(expires: expires) @token = token @expires = expires end
valid(expires:, cutoff: @@cutoff)
click to toggle source
# File lib/sc2cli/shared/token.rb, line 123 def valid(expires:, cutoff: @@cutoff) return (expires - @@cutoff) > Time.now end