Track Devise login activity
Track Devise login activity
:tangerine: Battle-tested at Instacart
Add this line to your application’s Gemfile:
gem "authtrail"To encrypt email and IP addresses with Lockbox, install Lockbox and Blind Index and run:
rails generate authtrail:install --encryption=lockbox
rails db:migrateTo use Active Record encryption, run:
rails generate authtrail:install --encryption=activerecord
rails db:migrateIf you prefer not to encrypt data, run:
rails generate authtrail:install --encryption=none
rails db:migrateTo enable geocoding, see the Geocoding section.
A LoginActivity record is created every time a user tries to login. You can then use this information to detect suspicious behavior. Data includes:
scope - Devise scopestrategy - Devise strategyidentity - email addresssuccess - whether the login succeededfailure_reason - if the login faileduser - the user if the login succeededcontext - controller and actionip - IP addressuser_agent and referrer - from browsercity, region, country, latitude, and longitude - from IPcreated_at - time of eventExclude certain attempts from tracking - useful if you run acceptance tests
AuthTrail.exclude_method = lambda do |data|
data[:identity] == "[email protected]"
endAdd or modify data - also add new fields to the login_activities table if needed
AuthTrail.transform_method = lambda do |data, request|
data[:request_id] = request.request_id
endStore the user on failed attempts
AuthTrail.transform_method = lambda do |data, request|
data[:user] ||= User.find_by(email: data[:identity])
endWrite data somewhere other than the login_activities table
AuthTrail.track_method = lambda do |data|
# code
endUse a custom identity method
AuthTrail.identity_method = lambda do |request, opts, user|
if user
user.email
else
request.params.dig(opts[:scope], :email)
end
endAssociate login activity with your user model
class User "]
data[:region] = request.headers[""]
data[:city] = request.headers[""]
endCheck out this example
Delete older data with:
LoginActivity.where("created_at < ?", 2.years.ago).in_batches.delete_allDelete data for a specific user with:
LoginActivity.where(user_id: 1, user_type: "User").in_batches.delete_allWe recommend using this in addition to Devise’s Lockable module and Rack::Attack.
Check out Hardening Devise and Secure Rails for more best practices.
View the changelog
Everyone is encouraged to help improve this project. Here are a few ways you can help:
To get started with development and testing:
git clone https://github.com/ankane/authtrail.git
cd authtrail
bundle install
bundle exec rake testNo open issues yet, or sync has not completed.