Skip to content

Instantly share code, notes, and snippets.

@davestevens
Last active August 29, 2015 14:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davestevens/fe88b1e2a1916e221d64 to your computer and use it in GitHub Desktop.
Save davestevens/fe88b1e2a1916e221d64 to your computer and use it in GitHub Desktop.
OAuth2 with Refresh Token
require "oauth2"
require_relative "token"
module Api
class Client
def initialize(client_id:, client_secret:, endpoint:)
@client_id = client_id
@client_secret = client_secret
@endpoint = endpoint
end
def token(options = {})
if ([:username, :password] - options.keys).empty?
password_token(options)
else
client_token
end
end
def client_token
Token.new(token: client.client_credentials.get_token)
end
def password_token(username:, password:)
Token.new(token: client.password.get_token(username, password))
end
private
attr_reader :client_id, :client_secret, :endpoint
def client
@_client ||= OAuth2::Client.new(client_id, client_secret, site: endpoint)
end
end
end
#!/usr/bin/env ruby
require_relative "client.rb"
require "pry"
client = Api::Client.new({
client_id: "",
client_secret: "",
endpoint: ""
})
puts "Client Token"
client_token = client.token
puts client_token.get("/version").body
puts "Sleep for expiry"
sleep client_token.expires_in + 1
puts client_token.get("/version").body
puts "Password Token"
password_token = client.token(username: "", password: "")
puts password_token.get("/version").body
puts "Sleep for expiry"
sleep password_token.expires_in + 1
puts password_token.get("/version").body
module Api
class Token
REQUEST_METHODS = %w(get put post delete request).freeze
def initialize(token:)
@token = token
end
REQUEST_METHODS.each do |method|
define_method(method) do |path, options: {}|
token.send(method, path, options)
end
end
private
def token
refresh_token if expired?
@token
end
def expired?
@token.expires_at <= Time.new.to_i
end
def refresh_token
if client_token?
@token = @token.client.client_credentials.get_token
else
@token = @token.refresh!
end
end
def client_token?
@token.refresh_token.nil?
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment