Last active
December 9, 2017 08:44
-
-
Save herenow/593bf85df610dad08612692ef3a76c66 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'uri' | |
require 'net/http' | |
require 'auth0' | |
class Auth0Api | |
def initialize(options = {}) | |
@client_id = options[:client_id] || ENV['AUTH0_CLIENT_ID'] | |
@client_secret = options[:client_secret] || ENV['AUTH0_CLIENT_SECRET'] | |
@domain = options[:domain] || ENV['AUTH0_DOMAIN'] | |
end | |
def client | |
@client ||= new_client | |
end | |
def token | |
@token ||= get_token | |
end | |
private | |
def new_client | |
Auth0Client.new( | |
client_id: @client_id, | |
client_secret: @client_secret, | |
domain: @domain, | |
token: token, | |
api_version: 2, | |
) | |
end | |
def get_token | |
# TODO: Maybe we should cache this api call? | |
get_token_data['access_token'] | |
end | |
def get_token_data | |
url = URI("https://#{@domain}/oauth/token") | |
http = Net::HTTP.new(url.host, url.port) | |
http.use_ssl = true | |
http.verify_mode = OpenSSL::SSL::VERIFY_NONE | |
request = Net::HTTP::Post.new(url) | |
request['content-type'] = 'application/json' | |
request.body = JSON.dump({ | |
grant_type: 'client_credentials', | |
client_id: @client_id, | |
client_secret: @client_secret, | |
audience: "https://#{@domain}/api/v2/", | |
}) | |
response = http.request(request) | |
check_http_response!(response) | |
data = JSON.parse(response.read_body) | |
data | |
end | |
def check_http_response!(response) | |
unless response.kind_of? Net::HTTPSuccess | |
puts response.read_body | |
response.error! | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment