Search code examples
ruby-on-railsdevise

Using Devise before_action :authenticate_user! doesn't do anything


I am trying to require login on all pages on my Rails 4 web site. In the ApplicationController I have added before_action :authenticate_user!, but it simply doesn't do anything. I have tried to add the same before_action :authenticate_user! to another controller, and it works fine.

Do I need to do something else to the ApplicationController, to make the login be required on all actions (Except signup/signin)?


Solution

  • Here's the actual code we use:

    #app/controllers/application_controller.rb
    Class ApplicationController < ActionController::Base
       #Actions
       before_action :authenticate_user! #-> routes to the login / signup if not authenticated
    end
    

    The problem you probably have is two-fold:

    --

    Make sure your other controllers are inheriting from application_controller:

    #app/controllers/other_controller.rb
    Class OtherController < ApplicationController 
        ...
    end
    

    --

    You're somehow "skipping" the before_action callback

    If you're using skip_before_action anywhere, you need to remove it. It will likely cause a problem with your authenticate_user! method. To fix this, I would firstly test without any skip_before_action callbacks, and then see what gets it working correctly


    A further note - signin / signup won't matter. They all inherit from the Devise controllers; they'll just run as required.