Created
December 11, 2017 20:35
-
-
Save brissmyr/54ff182ee72cd81bf4ab572f58b870d7 to your computer and use it in GitHub Desktop.
Tracking failed logins with Devise
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# routes.rb | |
Rails.application.routes.draw do | |
devise_for :users, controllers: { sessions: 'sessions' } | |
end | |
# sessions_controller.rb | |
class SessionsController < Devise::SessionsController | |
protected | |
def auth_options | |
# find the email field | |
key = serialize_options(resource)[:methods].first | |
email = sign_in_params[key] | |
# find the user if any | |
user = resource_class.find_for_authentication(key => email) | |
# make it available to Warden hooks | |
super.merge(email: email, user_id: user && user.id) | |
end | |
end | |
# config/initializers/warden.rb | |
Warden::Manager.before_failure do |env, opts| | |
if opts[:action] == 'unauthenticated' | |
castle = env['castle'] | |
begin | |
castle.track( | |
event: '$login.failed', | |
user_id: opts[:user_id], | |
properties: { | |
email: opts[:email] | |
} | |
) | |
rescue ::Castle::Error | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment