5

I'd like a simple method in my application controller that requires all users to log in before continuing to any part of the site. I'm using Devise for authentication.

I tried:

class ApplicationController < ActionController::Base
  ...
  unless user_signed_in?
    redirect_to login_path
  end
  ...
end

This successfully redirects everyone, but the problem is it also prevents the post request necessary to create a new user session.

So my question is, how would you go about blocking all requests except for the login view and the post request for logging in?

Andrew
  • 42,517
  • 51
  • 181
  • 281

1 Answers1

10

Using Devise this is easy. You just need to add before_filter :authenticate_user! to your ApplicationController.

This is all spelled out in the Devise wiki - https://github.com/plataformatec/devise

Note that in Rails 4.2+, before_action :authenticate_user! is preferred.

styger
  • 430
  • 3
  • 13
pcg79
  • 1,283
  • 9
  • 20
  • Oh of course. I have this in many (but not all) of the controllers already... I was thinking too hard about how to lock down the entire site temporarily and not thinking enough about application controller being just a regular controller. Thanks :) – Andrew Jul 13 '11 at 16:16
  • 3
    For the most part you'll want to just throw that line into ApplicationController and then skip the before filter for the actions you want to white list. – pcg79 Jul 13 '11 at 16:27