Ruby on Rails Devise code after login

whognu picture whognu · Jan 21, 2014 · Viewed 14.9k times · Source

I have an RoR app using Devise for logins. There is some code that is executed when a new User record is created, by being put in the user.rb file as an after_create call/macro/whatever. I need to make this code run after each login, instead of running on new user creation.

With some Googling, it seems that one option is to place Warden callbacks in the devise.rb code. My questions are:

  1. Is this right, and/or is there a better way to do this?
  2. If this is the right approach ...
    • Should the Warden::Manager... method defs go in devise.rb inside of Devise.setup, or after it?
    • Is after_authentication the callback I should use? I'm just checking to see if a directory based on the user's name exists, and if not, creating it.

Answer

Ashitaka picture Ashitaka · Jan 22, 2014

Just subclass Devise's sessions controller and put your custom behaviour there:

# config/routes.rb
devise_for :users, :controllers => { :sessions => "custom_sessions" }

And then create your controller like this:

# app/controllers/custom_sessions_controller.rb
class CustomSessionsController < Devise::SessionsController
  ## for rails 5+, use before_action, after_action
  before_filter :before_login, :only => :create
  after_filter :after_login, :only => :create

  def before_login
  end

  def after_login
  end
end