require "mvx_auth_client/version" require 'jwt' module MvxAuthClient class Error < StandardError; end @@auth_pub_key = nil AUTH_URL = (ENV['AUTH_URL'] || 'http://10.109.182.207:3030') class << self def request_token(login, password) json = {:login => login, :password => password } create_connection(AUTH_URL, '/login') res = send_request(json) token = JSON.parse(res.body)['login_token'] if token.blank? return nil end user_info = decrypt_token_full(token) if user_info.blank? return nil end opcode = user_info[:opcode] warehouseId = user_info[:warehouses].keys.first.to_s new_token_request = { warehouseId: warehouseId }.to_json cookie = 'Bearer ' + token uri = URI.parse(AUTH_URL + "/get_tokens") http = Net::HTTP.new(uri.host,uri.port, nil) req = Net::HTTP::Post.new(uri.path, initheader = {'Content-Type' =>'application/json'}) req['Authorization'] = cookie req.body = new_token_request res = http.request(req) json_reply_hash = JSON.parse(res.body) json_reply_hash[:opcode] = opcode return json_reply_hash end def decrypt_token_full(token, repeat_get_key = true) key = get_key(AUTH_URL, '/public_rsa') rsa_public = OpenSSL::PKey::RSA.new(key) begin return JWT.decode(token, rsa_public, true, algorithms: 'RS256').first.symbolize_keys rescue JWT::VerificationError => e if repeat_get_key @@auth_pub_key = nil return decrypt_token_full(token, false) else raise e end end return decoded end private def create_connection(env, method) url = ENV[env] || env url_method = url + method uri = URI.parse(url_method) @http = Net::HTTP.new(uri.host, uri.port, nil) #No proxy! @req = Net::HTTP::Post.new(uri.path, 'Content-Type' => 'application/json') end def send_request(body) # begin @req.body = body.to_json @http.request(@req) # rescue Exception => e # render json: {error: "Unauthorized"}.to_json, status: 401 # end end def get_key(env, method) if @@auth_pub_key.nil? uri = URI((ENV[env] || env) + method) http = Net::HTTP.new(uri.host, uri.port, nil) req = Net::HTTP::Get.new(uri.path, 'Content-Type' => 'application/json') response = http.request(req) body = response.body res = JSON.parse(body) @@auth_pub_key = res['public_rsa'] end @@auth_pub_key end def get_tokens(body, cookies) json = JSON.parse(body) companyId = json['companyId'] custCompanyId = json['custCompanyId'] warehouseId = json['warehouseId'] cookies['Authorization'] = cookies create_connection(method) resp = send_request({companyId: companyId, custCompanyId: custCompanyId, warehouseId: warehouseId}.to_json) return resp.body end end end