Class: Auth0MachineToMachine::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/auth0_machine_to_machine.rb

Instance Method Summary collapse

Instance Method Details

#getM2M(config) ⇒ Object



65
66
67
68
69
70
71
# File 'lib/auth0_machine_to_machine.rb', line 65

def getM2M(config)
  begin
    getM2M!(config)
  rescue Exception => e
    false
  end
end

#getM2M!(config) ⇒ Object



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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/auth0_machine_to_machine.rb', line 16

def getM2M!(config)
  tenant_name = config['tenant_name']
  client_id = config['client_id']
  client_secret = config['client_secret']
  audience = config['audience']
  grant_type = config['grant_type']

  url = URI("https://#{tenant_name}.eu.auth0.com/oauth/token")

  http = Net::HTTP.new(url.host, url.port)
  use_ssl = url.scheme == 'https'
  http.use_ssl = use_ssl
  if use_ssl
    http.verify_mode = OpenSSL::SSL::VERIFY_PEER
  else
    http.verify_mode = OpenSSL::SSL::VERIFY_NONE
  end

  request = Net::HTTP::Post.new(url)
  request["content-type"] = 'application/json'
  request["accept"] = 'application/json'

  body = {
    client_id: client_id,
    client_secret: client_secret,
    audience: audience,
    grant_type: grant_type
  }

  request.body = body.to_json

  response = http.request(request)

  if response.is_a?(Net::HTTPSuccess)
    body = JSON.parse(response.body)
    expires_in = body['expires_in']
    expire_date = Time.now + expires_in
    result = {
      access_token: body['access_token'],
      scope: body['scope'],
      expires_in: expires_in,
      expire_date: expire_date,
      token_type: body['token_type']
    }
  else
    raise GenericError.new(response.code + response.body + response.message)
  end
end