Skip to content

Instantly share code, notes, and snippets.

@cwsaylor
Forked from derwiki/README.md
Created March 3, 2016 17:43
Show Gist options
  • Save cwsaylor/4b813564336570add018 to your computer and use it in GitHub Desktop.
Save cwsaylor/4b813564336570add018 to your computer and use it in GitHub Desktop.
Ruby module that you can use in a `before_action` on sensitive controllers for which you'd like a usage audit trail

Adding an audit log to your Rails app

If you have any sort of administrative interface on your web site, you can easily imagine an intruder gaining access and mucking about. How do you know the extent of the damage? Adding an audit log to your app is one quick solution. An audit log should record a few things:

  • controller entry points with parameter values
  • permanent information about the user, like user_id
  • transient information about the user, like IP and user_agent

Using the Rails framework, this is as simple as adding a before_action to your admin controllers. Here’s a basic version that I’m using in production.

require 'audit_log'
class AdminController < ApplicationController
include AuditLog
before_action :auto_log
end
require 'geoip'
module AuditLog
def geoip
@@geoip ||= GeoIP.new(File.join(Rails.root, '/lib/GeoIPCity.dat'))
end
def auto_log
rails_action = "#{ params[:controller] }##{ params[:action] }"
rails_params = params.except(:controller, :action)
details = {
:logger => 'AuditLog',
:action => rails_action,
:ip_address => request.remote_ip,
:geo_ip => geoip.city(request.remote_ip).to_h,
:user_id => current_user&.id,
:user_email => current_user&.email,
:user_name => current_user&.name,
:params => rails_params,
:user_agent => request.user_agent
}
Rails.logger.info MultiJson.dump(details)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment