Class: LearnWorlds::AuthenticationResource

Inherits:
Resource
  • Object
show all
Defined in:
lib/learn_worlds/resources/authentication_resource.rb

Constant Summary collapse

AUTHENTICATE_ENDPOINT =
"/admin/api/oauth2/access_token".freeze
CLIENT_CREDENTIALS_GRANT_TYPE =
"client_credentials".freeze

Instance Attribute Summary

Attributes inherited from Resource

#client

Instance Method Summary collapse

Methods inherited from Resource

#default_headers, #delete_request, #get_request, #handle_errors, #handle_response, #initialize, #patch_request, #post_request, #put_request

Constructor Details

This class inherits a constructor from LearnWorlds::Resource

Instance Method Details

#authenticate(method) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
18
19
# File 'lib/learn_worlds/resources/authentication_resource.rb', line 6

def authenticate(method)
  custom_access_token_retrieval

  # everything went well don't need to continue
  return if client.access_token

  case method
  when CLIENT_CREDENTIALS_GRANT_TYPE
    authenticate_with_secret
  end

  # custom method to store the access token until it expires so we don't need to make uneccessary calls
  LearnWorlds.configuration.persist_access_token_method&.call(client.access_token, client.expires_in)
end

#authenticate_with_secretObject



31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/learn_worlds/resources/authentication_resource.rb', line 31

def authenticate_with_secret
  # get the access token using the api
  response = post_request(
    AUTHENTICATE_ENDPOINT,
    {
      client_id: client.client_id,
      client_secret: client.client_secret,
      grant_type: CLIENT_CREDENTIALS_GRANT_TYPE
    }
  )
  response_body = Object.new(response.body)
  client.access_token = response_body.tokenData.access_token
  client.expires_in = response_body.tokenData.expires_in
end

#custom_access_token_retrievalObject

custom retrieve method can be used if you store the access token on your side until it expires for example



22
23
24
25
26
27
28
29
# File 'lib/learn_worlds/resources/authentication_resource.rb', line 22

def custom_access_token_retrieval
  retrieve_access_token_method = LearnWorlds.configuration.retrieve_access_token_method

  return unless retrieve_access_token_method

  retrieved_access_token = retrieve_access_token_method.call
  client.access_token = retrieved_access_token
end