module LocalPac module App class LookupController < ApplicationController helpers Sinatra::Param get '/' do redirect to('/proxy.pac') end get '/:name' do file = local_storage.find(params[:name].to_s) fail Sinatra::NotFound, name: params[:name].to_s if file.nil? @client_ip = IPAddr.new(remote_addr).to_s @time = Time.now.strftime "%Y-%m-%d %H:%M:%S" haml :lookup, layout: :application end post '/:name' do param :name, String, required: true param :url, String, required: true param :client_ip, String param :time, String parse_env = {} @file = local_storage.find(params[:name]) @uri = Addressable::URI.heuristic_parse(params[:url]) fail Sinatra::NotFound, name: params[:name].to_s if @file.nil? fail Exceptions::GivenUrlInvalid, JSON.dump(url: params[:url]) if @uri.host.blank? begin parse_env[:time] = @time = Time.parse(params[:time]).to_s unless params[:time].blank? rescue ArgumentError raise Exceptions::GivenTimeInvalid, JSON.dump(time: params[:time]) end begin parse_env[:client_ip] = @client_ip = IPAddr.new(params[:client_ip]).to_s unless params[:client_ip].blank? rescue ArgumentError raise Exceptions::GivenClientIpInvalid, JSON.dump(client_ip: params[:client_ip]) end parser = LocalPac::ProxyPac::PacParser.new(file: @file, environment: parse_env) begin @result = parser.find(@uri) rescue Exceptions::PacFileInvalid raise Exceptions::PacFileInvalid, name: params[:name] end haml :lookup_result, layout: :application end helpers do def remote_addr return '127.0.0.1' if env['REMOTE_ADDR'] == '' return env['REMOTE_ADDR'] if env['REMOTE_ADDR'] '127.0.0.1' end end end end end