module Ecoportal module API module Common module GraphQL module AuthService DEFAULT_SERVER = "live.ecoportal.com".freeze TOKEN_AUTORENEW = 90 # minutes module InstanceMethods def session_token(host: server, version: nil, auto_renew: true) session_token_data(host: host, version: version).then do |body| next unless body if auto_renew && token_renew?(body["expires_in"]) session_token_renewed( host: host, version: version, refresh_token: body["refresh_token"] ) else body["access_token"] end end end def session_token_renewed(host: server, version: nil, refresh_token: nil) unless refresh_token return unless (body = session_token_data(host: host, version: version)) return unless (refresh_token = body["resfresh_token"]) end session_refresh_token_data( host: host, version: version, refresh_token: refresh_token ).then do |bdy| bdy["access_token"] if bdy end end private def session_token_data(host: server, version: nil) http_client(host: host, version: version).post( "/oauth/token", data: { "grant_type" => "password", "email" => user_email, "password" => user_pass } ).then do |response| next response.body if response.success? end end def session_refresh_token_data(refresh_token:, host: server, version: nil) http_client(host: host, version: version).post( "/oauth/token", data: { "grant_type" => "refresh_token", "refresh_token" => refresh_token } ).then do |response| next response.body if response.success? end end def token_renew?(seconds) (TOKEN_AUTORENEW * 60) > seconds end def http_client(host: server, version: nil) @http_client ||= Ecoportal::API::Common::GraphQL::HttpClient.new( host: host, version: version ) end def user_email @user_email || fetch_env_required("USER_EMAIL") end def user_pass @user_pass || fetch_env_required("USER_PASS") end def server(default = DEFAULT_SERVER) ENV['SERVER'] || default end def fetch_env_required(name) abort("Missing ENV '#{name}'") unless ENV.key?(name) ENV[name] end def abort(msg) puts msg exit(1) end end module ClassMethods end class << self include InstanceMethods def included(base) base.send(:include, InstanceMethods) base.extend(ClassMethods) end end end end end end end