Module: Elmas::OAuth

Included in:
API
Defined in:
lib/elmas/oauth.rb

Instance Method Summary collapse

Instance Method Details

#authorize(user_name, password, options = {}) ⇒ Object



11
12
13
14
15
16
17
18
19
# File 'lib/elmas/oauth.rb', line 11

def authorize(user_name, password, options = {})
  agent = Mechanize.new

  (agent, user_name, password, options)
  allow_access(agent)

  code = URI.unescape(agent.page.uri.query.split("=").last)
  OauthResponse.new(get_access_token(code))
end

#authorize_divisionObject



29
30
31
# File 'lib/elmas/oauth.rb', line 29

def authorize_division
  get("/Current/Me", no_division: true).results.first.current_division
end

#authorize_url(options = {}) ⇒ Object

Return URL for OAuth authorization



47
48
49
50
51
52
53
54
# File 'lib/elmas/oauth.rb', line 47

def authorize_url(options = {})
  options[:response_type] ||= "code"
  options[:redirect_uri] ||= redirect_uri
  params = authorization_params.merge(options)
  uri = URI("https://start.exactonline.nl/api/oauth2/auth/")
  uri.query = URI.encode_www_form(params)
  uri.to_s
end

#authorized?Boolean

Returns:

  • (Boolean)


21
22
23
24
25
26
27
# File 'lib/elmas/oauth.rb', line 21

def authorized?
  # Do a test call, return false if 401 or any error code
  get("/Current/Me", no_division: true)
rescue BadRequestException
  Elmas.error "Not yet authorized"
  return false
end

#auto_authorizeObject



33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/elmas/oauth.rb', line 33

def auto_authorize
  Elmas.configure do |config|
    config.client_id = ENV["CLIENT_ID"]
    config.client_secret = ENV["CLIENT_SECRET"]
  end
  Elmas.configure do |config|
    config.access_token = Elmas.authorize(ENV["EXACT_USER_NAME"], ENV["EXACT_PASSWORD"]).access_token
  end
  Elmas.configure do |config|
    config.division = Elmas.authorize_division
  end
end

#get_access_token(code, _options = {}) ⇒ Object

Return an access token from authorization



57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/elmas/oauth.rb', line 57

def get_access_token(code, _options = {})
  conn = Faraday.new(url: "https://start.exactonline.nl") do |faraday|
    faraday.request :url_encoded
    faraday.adapter Faraday.default_adapter
  end
  params = access_token_params(code)
  conn.post do |req|
    req.url "/api/oauth2/token"
    req.body = params
    req.headers["Accept"] = "application/json"
  end
end