Class: Alula::Oauth

Inherits:
Object
  • Object
show all
Includes:
HTTParty
Defined in:
lib/alula/oauth.rb

Defined Under Namespace

Classes: Error, Response

Class Method Summary collapse

Class Method Details

.authenticate(username: nil, password: nil, grant_type: :password, scopes: nil) ⇒ Object



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
# File 'lib/alula/oauth.rb', line 18

def authenticate(username: nil, password: nil, grant_type: :password, scopes: nil)
  raise Alula::NotConfiguredError.new('did you forget to call Alula::Oauth.configure ?') unless api_url

  raise Alula::NotConfiguredError.new('no scopes specified') if grant_type.to_sym == :client_credentials && (scopes.nil? || scopes == '')

  opts = {
    body: {
      grant_type: grant_type.to_s,
      client_id: client_id,
      client_secret: client_secret,
    }
  }

  if grant_type == :password
    opts[:body][:username] = username if username
    opts[:body][:password] = password if password
  end

  opts[:body][:scope] = scopes if grant_type.to_sym == :client_credentials

  if self.debug
    opts[:debug_output] = Alula.logger 
    # sets the HTTParty logger
    logger Alula.logger, :info
  end

  response = post(api_url + '/oauth/token', opts)

  if response.ok?
    Response.new(response.parsed_response)
  else
    Error.new(response.parsed_response)
  end
end

.configure(**config) ⇒ Object

Has pseudo attr readers :client_id, :client_secret, :api_url, :debug



10
11
12
13
14
15
16
# File 'lib/alula/oauth.rb', line 10

def configure(**config)
  self.api_url = config[:api_url]
  self.client_id = config[:client_id]
  self.client_secret = config[:client_secret]
  self.debug = config[:debug] == true
  nil
end

.refresh(refresh_token:, access_token:) ⇒ Object



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
# File 'lib/alula/oauth.rb', line 53

def refresh(refresh_token:, access_token:)
  opts = {
    body: {
      grant_type: 'refresh_token',
      client_id: client_id,
      client_secret: client_secret,
      refresh_token: refresh_token,
    },
    headers: {
      'Authorization:': "Bearer #{access_token}"
    }
  }

  if self.debug == true
    opts[:debug_output] = Alula.logger
  end

  response = post(api_url + '/oauth/token', opts)

  if response.ok?
    Response.new(response.parsed_response)
  else
    Error.new(response.parsed_response)
  end
end