lib/rack/simple_auth/hmac.rb in rack-simple_auth-0.0.3 vs lib/rack/simple_auth/hmac.rb in rack-simple_auth-0.0.4
- old
+ new
@@ -5,15 +5,16 @@
class HMAC
# Constructor for Rack Middleware (passing the rack stack)
# @param [Rack Application] app [next middleware or rack app which gets called]
# @param [String] signature [Public Signature]
# @param [String] secret [Secret used for Message Encryption]
- def initialize(app, signature, secret, config)
+ def initialize(app, signature, secret, config, logpath = nil)
@app = app
@signature = signature
@secret = secret
@config = config
+ @logpath = logpath
end
# call Method for Rack Middleware/Application
# @param [Hash] env [Rack Env Hash which contains headers etc..]
def call(env)
@@ -28,24 +29,27 @@
# checks for valid HMAC Request
# @param [Rack::Request] request [current Request]
# @return [boolean] ValidationStatus [If authorized returns true, else false]
def valid?(request)
- return false if request.env['HTTP_AUTHORIZATION'].nil?
+ if request.env['HTTP_AUTHORIZATION'].nil?
+ log(request)
+ return false
+ end
+
auth_array = request.env['HTTP_AUTHORIZATION'].split(':')
message_hash = auth_array[0]
signature = auth_array[1]
- hash = OpenSSL::HMAC.hexdigest(OpenSSL::Digest::Digest.new('sha256'), @secret, message(request))
- # puts request.request_method
- # puts "Hash to Check: #{hash}"
- # puts "Message Hash: #{message_hash}"
+ @hash = OpenSSL::HMAC.hexdigest(OpenSSL::Digest::Digest.new('sha256'), @secret, message(request))
- if signature == @signature && hash == message_hash
+ if signature == @signature && @hash == message_hash
true
else
+ log(request)
+
false
end
end
# Get Message for current Request
@@ -75,8 +79,28 @@
request.send(config[request.request_method].to_sym)
else
fail "Not a valid option #{config[request.request_method]} - Use either params or path"
end
end
+
+ # Log to @logpath if request is unathorized
+ # @param [Rack::Request] request [current Request]
+ def log(request)
+ if @logpath
+ path = request.path
+ method = request.request_method
+
+ log = "#{Time.new} - #{method} #{path} - 400 Unauthorized - HTTP_AUTHORIZATION: #{request.env['HTTP_AUTHORIZATION']}\n"
+ log << "Auth Message Config: #{@config[request.request_method]}\n"
+ log << "Auth Encrypted Message: #{@hash}\n"
+ log << "Auth Signature: #{@signature}\n"
+
+ open("#{@logpath}/#{ENV['RACK_ENV']}_error.log", 'a') do |f|
+ f << "#{log}\n"
+ end
+ end
+ end
+
+ private :log, :request_data, :message, :valid?
end
end
end