class MdNotes::OAuth2
Utility class for OAuth 2 authorization and token management.
Public Class Methods
apply(config, http_request)
click to toggle source
Add OAuth2
authentication to the http request. @param [HttpRequest] The HttpRequest
object to which authentication will be added.
# File lib/md_notes/http/auth/o_auth2.rb, line 18 def self.apply(config, http_request) check_auth config.o_auth_token token = config.o_auth_token.access_token http_request.headers['Authorization'] = "Bearer #{token}" end
auth_controller(config)
click to toggle source
# File lib/md_notes/http/auth/o_auth2.rb, line 11 def self.auth_controller(config) OAuthAuthorizationController.new config end
build_basic_auth_header(config)
click to toggle source
Builds the basic auth header for endpoints in the OAuth Authorization Controller.
# File lib/md_notes/http/auth/o_auth2.rb, line 42 def self.build_basic_auth_header(config) value = "#{config.o_auth_client_id}:" \ "#{config.o_auth_client_secret}" encoded = Base64.strict_encode64(value) "Basic #{encoded}" end
check_auth(token)
click to toggle source
Checks if OAuth token is valid.
# File lib/md_notes/http/auth/o_auth2.rb, line 50 def self.check_auth(token) # Check if OAuth token exists. if token.nil? raise 'Client is not authorized. An OAuth token is needed to ' \ 'make API calls.' # Check if OAuth token has expired. elsif token.expiry && token.expiry < Time.now.to_i raise 'The OAuth token has expired. Please refresh the existing token' \ ' or generate a new one.' end end
refresh_token(config, scope: nil, additional_params: nil)
click to toggle source
Refreshes OAuth token and returns it. You must then set it in your Configuration
object. @param [String | Array of String] Any scopes for the new authentication token. @param [Hash] Any additional form parameters.
# File lib/md_notes/http/auth/o_auth2.rb, line 67 def self.refresh_token(config, scope: nil, additional_params: nil) token = auth_controller(config).refresh_token( build_basic_auth_header(config), config.o_auth_token.refresh_token, scope: scope ? Array(scope).compact.join(' ') : nil, _field_parameters: additional_params ) token.expiry = (Time.now.to_i + token.expires_in.to_i) if token.expires_in token end