Class: Apadmi::Grout::ConfluenceAuthService

Inherits:
Object
  • Object
show all
Defined in:
lib/apadmi/grout/service/confluence_auth_service.rb

Overview

Handles fetching and caching of Confluence OAuth tokens

Instance Method Summary collapse

Constructor Details

#initialize(client_id, client_secret, conn = Faraday.new) ⇒ ConfluenceAuthService

Returns a new instance of ConfluenceAuthService.



10
11
12
13
14
15
16
# File 'lib/apadmi/grout/service/confluence_auth_service.rb', line 10

def initialize(client_id, client_secret, conn = Faraday.new)
  @client_id = client_id
  @client_secret = client_secret
  @conn = conn
  @token = nil
  @token_expires_at = nil
end

Instance Method Details

#auth_headerObject



18
19
20
21
# File 'lib/apadmi/grout/service/confluence_auth_service.rb', line 18

def auth_header
  fetch_new_token if @token.nil? || @token_expires_at.nil? || Time.now >= @token_expires_at
  "Bearer #{@token}"
end

#fetch_new_tokenObject



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/apadmi/grout/service/confluence_auth_service.rb', line 23

def fetch_new_token
  response = @conn.post("https://api.atlassian.com/oauth/token") do |req|
    req.headers["Content-Type"] = "application/json"
    req.body = JSON.dump({
                           "grant_type" => "client_credentials",
                           "client_id" => @client_id,
                           "client_secret" => @client_secret
                         })
  end

  throw_if_error(response)
  json = JSON.parse(response.body)
  @token = json["access_token"]
  @token_expires_at = Time.now + json["expires_in"].to_i
end

#throw_if_error(response) ⇒ Object



39
40
41
# File 'lib/apadmi/grout/service/confluence_auth_service.rb', line 39

def throw_if_error(response)
  raise "Network call failed #{response.status} #{response.body}" unless (200..210).include?(response.status)
end