Class: Oneaws::Client

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

Defined Under Namespace

Classes: MfaDeviceNotFoundError, SamlRequestError

Instance Method Summary collapse

Constructor Details

#initializeClient

Returns a new instance of Client.



10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/oneaws/client.rb', line 10

def initialize
  @onelogin = OneLogin::Api::Client.new({
    client_id: ENV['ONELOGIN_CLIENT_ID'],
    client_secret: ENV['ONELOGIN_CLIENT_SECRET'],
    region: ENV['ONELOGIN_REGION'] || 'us',
  })

  @aws = Aws::STS::Client.new(
    credentials: Aws::AssumeRoleCredentials,
    region: ENV['AWS_REGION'] || 'ap-northeast-1',
  )
end

Instance Method Details

#issue_credential(options) ⇒ Object



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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# File 'lib/oneaws/client.rb', line 23

def issue_credential(options)
  username = options[:username]
  password = options[:password]
  app_id = options[:app_id]
  subdomain = options[:subdomain]
  response = @onelogin.get_saml_assertion(username, password, app_id, subdomain)
  if response.nil?
    raise SamlRequestError.new("#{@onelogin.error} #{@onelogin.error_description}")
  end

  mfa = response.mfa
  
  if mfa.devices.length == 1
    mfa_device = mfa.devices.first
  else
    puts "\nAvailable MFA devices:"
    mfa.devices.each_with_index do |device, index|
      puts "#{index + 1}. #{device.type} (ID: #{device.id})"
    end

    print "\nSelect MFA device (1-#{mfa.devices.length}): "
    selection = STDIN.gets.chomp.to_i

    if selection < 1 || selection > mfa.devices.length
      raise MfaDeviceNotFoundError.new("Invalid device selection.")
    end

    mfa_device = mfa.devices[selection - 1]
  end

  device_types_that_do_not_require_token = [
    "OneLogin Protect"
  ]

  otp_token = unless device_types_that_do_not_require_token.include?(mfa_device.type)
    print "input OTP of #{mfa_device.type}: "
    STDIN.noecho(&:gets)
  end

  response = @onelogin.get_saml_assertion_verifying(app_id, mfa_device.id, mfa.state_token, otp_token, nil, false)
  
  if response.nil?
    raise SamlRequestError.new("#{@onelogin.error} #{@onelogin.error_description}")
  end

  while response.type != "success" do
    sleep 1
    response = @onelogin.get_saml_assertion_verifying(app_id, mfa_device.id, mfa.state_token, nil, nil, true)
    if response.nil?
      raise SamlRequestError.new("#{@onelogin.error} #{@onelogin.error_description}")
    end
  end

  saml_assertion = response.saml_response

  params = {
    duration_seconds: (ENV['DURATION_SECONDS'] || 3600).to_i,
    principal_arn: ENV['AWS_PRINCIPAL_ARN'],
    role_arn: ENV['AWS_ROLE_ARN'],
    saml_assertion: saml_assertion,
  }
  @aws.assume_role_with_saml(params)[:credentials]
end