Class: Aspera::OAuth::Base

Inherits:
Object
  • Object
show all
Defined in:
lib/aspera/oauth/base.rb

Overview

OAuth 2 client for the REST client Generate bearer token Bearer tokens are cached in memory and in a file cache for later re-use OAuth 2.0 Authorization Framework: tools.ietf.org/html/rfc6749 Bearer Token Usage: tools.ietf.org/html/rfc6750

Direct Known Subclasses

FaspexPubLink, Generic, Jwt, UrlJson, Web

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(client_id: nil, client_secret: nil, scope: nil, use_query: false, path_token: 'token', token_field: Factory::TOKEN_FIELD, cache_ids: nil, **rest_params) ⇒ Base

Returns a new instance of Base.

Parameters:

  • **

    Parameters for REST

  • client_id (String, nil) (defaults to: nil)
  • client_secret (String, nil) (defaults to: nil)
  • scope (String, nil) (defaults to: nil)
  • use_query (bool) (defaults to: false)

    Provide parameters in query instead of body

  • path_token (String) (defaults to: 'token')

    API end point to create a token from base URL

  • token_field (String) (defaults to: Factory::TOKEN_FIELD)

    Field in result that contains the token

  • cache_ids (Array, nil) (defaults to: nil)

    List of unique identifiers for cache id generation



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/aspera/oauth/base.rb', line 25

def initialize(
  client_id: nil,
  client_secret: nil,
  scope: nil,
  use_query: false,
  path_token:  'token',
  token_field: Factory::TOKEN_FIELD,
  cache_ids: nil,
  **rest_params
)
  # This is the OAuth API
  @api = Rest.new(**rest_params)
  @scope = nil
  @token_cache_id = nil
  @path_token = path_token
  @token_field = token_field
  @client_id = client_id
  @client_secret = client_secret
  @use_query = use_query
  @base_cache_ids = cache_ids.nil? ? [] : cache_ids.clone
  Aspera.assert_type(@base_cache_ids, Array)
  # TODO: this shall be done in class, using cache_ids
  @base_cache_ids.push(@api.auth_params[:username]) if @api.auth_params.key?(:username)
  @base_cache_ids.compact!
  @base_cache_ids.freeze
  self.scope = scope
end

Instance Attribute Details

#apiObject (readonly)

Returns the value of attribute api.



60
61
62
# File 'lib/aspera/oauth/base.rb', line 60

def api
  @api
end

#client_idObject (readonly)

Returns the value of attribute client_id.



60
61
62
# File 'lib/aspera/oauth/base.rb', line 60

def client_id
  @client_id
end

#path_tokenObject (readonly)

Returns the value of attribute path_token.



60
61
62
# File 'lib/aspera/oauth/base.rb', line 60

def path_token
  @path_token
end

#scopeObject

Returns the value of attribute scope.



60
61
62
# File 'lib/aspera/oauth/base.rb', line 60

def scope
  @scope
end

Instance Method Details

#authorization(**kwargs) ⇒ Object

Returns value suitable for Authorization header.

Returns:

  • value suitable for Authorization header



94
95
96
# File 'lib/aspera/oauth/base.rb', line 94

def authorization(**kwargs)
  return OAuth::Factory.bearer_authorization(token(**kwargs))
end

#create_token_call(creation_params) ⇒ Object

helper method to create token as per RFC



63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# File 'lib/aspera/oauth/base.rb', line 63

def create_token_call(creation_params)
  Log.log.debug{'Generating a new token'.bg_green}
  payload = if @use_query
    {
      query: creation_params
    }
  else
    {
      content_type: Rest::MIME_WWW,
      body:         creation_params
    }
  end
  return @api.call(
    operation: 'POST',
    subpath:   @path_token,
    headers:   {'Accept' => Rest::MIME_JSON},
    **payload
  )
end

#optional_scope_client_id(add_secret: false) ⇒ Hash

Returns Optional general parameters.

Parameters:

  • add_secret (Boolean) (defaults to: false)

    Add secret in default call parameters

Returns:

  • (Hash)

    Optional general parameters



85
86
87
88
89
90
91
# File 'lib/aspera/oauth/base.rb', line 85

def optional_scope_client_id(add_secret: false)
  call_params = {}
  call_params[:scope] = @scope unless @scope.nil?
  call_params[:client_id] = @client_id unless @client_id.nil?
  call_params[:client_secret] = @client_secret unless !add_secret || @client_id.nil? || @client_secret.nil?
  return call_params
end

#token(cache: true, refresh: false) ⇒ Object

get an OAuth v2 token (generated, cached, refreshed) call token() to get a token. if a token is expired (api returns 4xx), call again token(refresh: true)

Parameters:

  • cache (defaults to: true)

    set to false to disable cache

  • refresh (defaults to: false)

    set to true to force refresh or re-generation (if previous failed)



103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
# File 'lib/aspera/oauth/base.rb', line 103

def token(cache: true, refresh: false)
  # get token info from cache (or nil), decoded with date and expiration status
  token_info = Factory.instance.get_token_info(@token_cache_id) if cache
  token_data = nil
  unless token_info.nil?
    token_data = token_info[:data]
    # Optional optimization:
    # Check if token is expired based on decoded content then force refresh if close enough
    # might help in case the transfer agent cannot refresh himself
    # `direct` agent is equipped with refresh code
    # an API was already called, but failed, we need to regenerate or refresh
    if refresh || token_info[:expired]
      Log.log.trace1{"refresh: #{refresh} expired: #{token_info[:expired]}"}
      refresh_token = nil
      if token_data.key?('refresh_token') && !token_data['refresh_token'].eql?('not_supported')
        # save possible refresh token, before deleting the cache
        refresh_token = token_data['refresh_token']
      end
      # delete cache
      Factory.instance.persist_mgr.delete(@token_cache_id)
      token_data = nil
      # lets try the existing refresh token
      if !refresh_token.nil?
        Log.log.info{"refresh=[#{refresh_token}]".bg_green}
        # NOTE: AoC admin token has no refresh, and lives by default 1800secs
        resp = create_token_call(optional_scope_client_id(add_secret: true).merge(grant_type: 'refresh_token', refresh_token: refresh_token))
        if resp[:http].code.start_with?('2')
          # save only if success
          json_data = resp[:http].body
          token_data = JSON.parse(json_data)
          Factory.instance.persist_mgr.put(@token_cache_id, json_data)
        else
          Log.log.debug{"refresh failed: #{resp[:http].body}".bg_red}
        end
      end
    end
  end

  # no cache, nor refresh: generate a token
  if token_data.nil?
    resp = create_token
    json_data = resp[:http].body
    token_data = JSON.parse(json_data)
    Factory.instance.persist_mgr.put(@token_cache_id, json_data)
  end
  Aspera.assert(token_data.key?(@token_field)){"API error: No such field in answer: #{@token_field}"}
  # ok we shall have a token here
  return token_data[@token_field]
end