Skip to content

Instantly share code, notes, and snippets.

@brissmyr
Last active January 24, 2018 17:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brissmyr/60313310ceddc012ff9304d664ec36a8 to your computer and use it in GitHub Desktop.
Save brissmyr/60313310ceddc012ff9304d664ec36a8 to your computer and use it in GitHub Desktop.
Tracking Castle login events through Warden hooks
# In Rails you would but this is in config/initializers/castle.rb
# Track $login.succeeded
Warden::Manager.after_set_user :except => :fetch do |user, warden, opts|
next unless opts[:scope] == :user # exclude e.g. admin users
castle = Castle::Client.from_request(warden.request)
begin
castle.track(
user_id: user.id,
event: '$login.succeeded',
traits: {
email: user.email,
created_at: user.created_at
}
)
rescue ::Castle::Error => e
end
end
# Track $login.failed
Warden::Manager.on_request do |warden, opts|
next unless [
'/users/sign_in', # e.g. web
'/api/sessions' # e.g. mobile, token auth
].include?(warden.request.headers['PATH_INFO'])
# IMPLEMENT: update to your form structure
next unless warden.request.params['user']
email = warden.request.params['user']['email']
password = warden.request.params['user']['password']
user = User.find_by_email(email)
next if user.present? && user.valid_password?(password)
castle = Castle::Client.from_request(warden.request)
begin
castle.track(
user_id: user && user.id,
event: '$login.failed',
details: {
email: email
}
)
rescue ::Castle::Error => e
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment