Dofs
Dofs

Reputation: 19317

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)?

Upvotes: 9

Views: 27740

Answers (2)

Praveen KJ
Praveen KJ

Reputation: 650

UPDATED 2019

In your routes.rb file you may have mentioned only authenticated_user path like below

authenticated :user do
    root to: 'home#index', as: :root_app
  end

You should mention unauthenticated_user path too to make it work or just root path without unauthenticated_user or authenticated_user

Upvotes: 2

Richard Peck
Richard Peck

Reputation: 76784

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.

Upvotes: 20

Related Questions