Search code examples
ruby-on-railsdeviseremember-me

Rails + Devise: How can I check if a user is remembered when signing in


How can I find out if a user who is signing in was remembered through an older session.

I found this answer: Rails/Devise: execute action after automatic login and it says that the after_remembered method gets called after a user was remembered. I tried it out and put it in my model but it doesn't get called. I even put a binding.pry before this line https://github.com/plataformatec/devise/blob/master/lib/devise/strategies/rememberable.rb#L30 but the whole authenticate! method doesn't even get called when signing in.

I hope someone can help


Solution

  • Okay, my previous idea with creating an after_update callback didn't work since it wouldn't get updated on an remembered session.

    What I ended up doing isn't really pretty, but I also didn't want to monkeypatch warden.

    class Users::SessionsController < Devise::SessionsController
      around_action :check_remembered, only: :create
    
      def create
        super
      end
    
      private
      def check_remembered
        # find the user based on the email in the login params. 
        # You can't use current_user here because once you call it, 
        # it will update the user before the action even ran (no idea why)
        user = User.find_by_email(params[:user][:email])
        yield
        if user && user.sign_in_count != current_user.sign_in_count
          # user was not remembered
        end
      end
     end
    

    For email only sign ins this is enough. If you are using omniauth sign ins then you have to block every omniauth sign in in the check_remembered function by checking if params[:user][:email] is present. Those will have to be handled in your omniauth controller.