Skip to content

Instantly share code, notes, and snippets.

@davout
Created May 26, 2014 11:13
Show Gist options
  • Save davout/edb4db0315dc417fa78d to your computer and use it in GitHub Desktop.
Save davout/edb4db0315dc417fa78d to your computer and use it in GitHub Desktop.
Persistent OAuth2 token client
#
# How to use :
# bc_client = AutoRefreshToken.new
# bc_client.post('/api/v1/user/orders', params.to_json)
#
require 'oauth2'
class AutoRefreshToken
BC_APP_KEY = 'xxx'
BC_APP_SECRET = 'xxx'
EXPIRATION_TIME = 1200
TOKEN_FILE = File.expand_path('~/.bot/token.json')
def initialize
self.token = get_initial_token
persist!
end
def get(uri)
token.get(uri)
end
def post(uri, data)
token.post(uri, body: data, headers: { "Content-Type" => "application/json" })
end
def token
@last_request ||= Time.now
if (Time.now - @last_request) > EXPIRATION_TIME
@last_request = Time.now
refresh!
end
@token
end
def token=(t)
@token = t
persist!
end
def get_initial_token
authorization_code = nil
client = OAuth2::Client.new(BC_APP_KEY, BC_APP_SECRET, site: 'https://bitcoin-central.net', authorize_url: '/api/oauth/authorize', token_url: '/api/oauth/token')
if File.exist?(TOKEN_FILE)
@token = OAuth2::AccessToken.from_hash(client, read_from_file)
refresh!
else
url = client.auth_code.authorize_url(redirect_uri: 'https://bitcoin-central.net/page/oauth/test', scope: 'basic activity trade withdraw')
system("open \"#{url}\"")
puts "Put the token in authorization_code and exit prompt"
binding.pry
@last_request = Time.now
self.token = client.auth_code.get_token(authorization_code, redirect_uri: 'https://bitcoin-central.net/page/oauth/test')
end
@token
end
def read_from_file
JSON.load(File.read(TOKEN_FILE))
end
def persist!
File.open(TOKEN_FILE, 'wb') { |f| f.write(@token.to_json) }
end
def refresh!
self.token = token.refresh!
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment