Skip to content

Instantly share code, notes, and snippets.

@derwiki
Last active Nov 21, 2020
Embed
What would you like to do?
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
@bertomartin
Copy link

bertomartin commented Mar 3, 2016

nice idea. you could probably dump this in redis (or any other fast in-memory db).

@gregnavis
Copy link

gregnavis commented Mar 4, 2016

Be careful with sensitive information (passwords, etc.).

@rainchen
Copy link

rainchen commented Mar 8, 2016

this module can be defined as a controller concern, then you can move before_action :auto_log in it

@velobuff
Copy link

velobuff commented Mar 9, 2016

👍 for using the lonely operator

@codemilan
Copy link

codemilan commented Mar 11, 2016

Awesome, nice trick.

@yyandrew
Copy link

yyandrew commented Mar 28, 2016

Really helpful

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment