Class: TimeDoctor::Token

Inherits:
Object
  • Object
show all
Defined in:
lib/timedoctor/token.rb

Constant Summary collapse

ENTRY =
'https://webapi.timedoctor.com/oauth/v2/token'.freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(config) ⇒ Token

Returns a new instance of Token.



5
6
7
# File 'lib/timedoctor/token.rb', line 5

def initialize(config)
  @config = config
end

Instance Attribute Details

#configObject (readonly)

Returns the value of attribute config.



9
10
11
# File 'lib/timedoctor/token.rb', line 9

def config
  @config
end

Instance Method Details

#fetchObject



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/timedoctor/token.rb', line 11

def fetch
  response = Faraday.get ENTRY,
                         client_id:     config[:client_id],
                         client_secret: config[:client_secret],
                         code:          config[:code],
                         redirect_uri:  config[:redirect_uri],
                         grant_type:    :authorization_code,
                         _format:       :json

  data = JSON.parse(response.body, symbolize_names: true)

  case response.status
  when 200
    config[:access_token]  = data[:access_token]
    config[:refresh_token] = data[:refresh_token]
    config[:on_token_authorize].call(data, config)
    data
  when 400
    config[:on_token_authorize_error].call(data, config)
    nil
  else
    raise UnknownError, response
  end
end

#refreshObject



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/timedoctor/token.rb', line 36

def refresh
  response = Faraday.get ENTRY,
                         refresh_token: config[:refresh_token],
                         client_id:     config[:client_id],
                         client_secret: config[:client_secret],
                         grant_type:    :refresh_token,
                         _format:       :json

  data = JSON.parse(response.body, symbolize_names: true)

  case response.status
  when 200
    config[:access_token]  = data[:access_token]
    config[:refresh_token] = data[:refresh_token]
    config[:on_token_refresh].call(data, config)
    data
  when 400
    config[:on_token_refresh_error].call(data, config)
    nil
  else
    raise UnknownError, response
  end
end