Class: HammerCLIForeman::OpenidConnect

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

Instance Method Summary collapse

Constructor Details

#initialize(url, oidc_client_id) ⇒ OpenidConnect

Returns a new instance of OpenidConnect.



5
6
7
8
# File 'lib/hammer_cli_foreman/openid_connect.rb', line 5

def initialize(url, oidc_client_id)
  @url = url
  @oidc_client_id = oidc_client_id
end

Instance Method Details

#get_token(username, password) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/hammer_cli_foreman/openid_connect.rb', line 10

def get_token(username, password)
  uri = URI.parse(@url)
  return nil unless uri.respond_to?(:request_uri)

  request = Net::HTTP::Post.new(uri)
  request.content_type = 'application/x-www-form-urlencoded'
  request.set_form_data(
    'username' => username,
    'password' => password,
    'grant_type' => 'password',
    'client_id' => @oidc_client_id
  )
  response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |https|
    https.request(request)
  end
  json_response = JSON.parse(response.body)
  if json_response.is_a?(Hash)
    json_response['access_token']
  else
    raise _("Invalid access token response.")
    nil
  end
rescue JSON::ParserError => e
  raise _('Invalid access token')
  nil
rescue Timeout::Error, Errno::EINVAL, Errno::ECONNRESET, EOFError,
    Net::HTTPBadResponse, Net::HTTPHeaderSyntaxError, Net::ProtocolError => e
  raise _("Failed to recieve acess token, please check your connectivity with OpenID provider: %s") % e
  nil
end

#get_token_via_2fa(code, oidc_redirect_uri) ⇒ Object



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/hammer_cli_foreman/openid_connect.rb', line 41

def get_token_via_2fa(code, oidc_redirect_uri)
  uri = URI.parse(@url)
  request = Net::HTTP::Post.new(uri)
  request.content_type = 'application/x-www-form-urlencoded'
  request.set_form_data(
    'client_id' => @oidc_client_id,
    'code' => code,
    'grant_type' => 'authorization_code',
    'redirect_uri' => oidc_redirect_uri
  )
  response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |https|
    https.request(request)
  end
  json_response = JSON.parse(response.body)
  if json_response.is_a?(Hash)
    json_response['access_token']
  else
    raise _("Invalid access token response.")
    nil
  end
rescue JSON::ParserError => e
  raise _('Invalid access token')
  nil
rescue Timeout::Error, Errno::EINVAL, Errno::ECONNRESET, EOFError,
    Net::HTTPBadResponse, Net::HTTPHeaderSyntaxError, Net::ProtocolError => e
  raise _("Failed to recieve acess token, please check your connectivity with OpenID provider: %s") % e
  nil
end