How To: Require authentication for all pages

Maxim edited this page Jan 15, 2016 · 6 revisions
Clone this wiki locally

In case your app requires users to be authenticated for all pages and to avoid the "You need to sign in or sign up before continuing." message when trying to access the application root, add this to your routes.rb:

authenticated :user do
  root to: 'home#index', as: :authenticated_root
end
root to: redirect('/users/sign_in')

In case your app has only omniauthable but no database_authenticatable, then the path /users/sign_in would not make sense. Something like following might suit well in such case:

authenticated :user do
  root to: 'home#dashboard', as: :authenticated_root
end
root to: 'home#landing'

Route Naming Note

As of Rails 4+, two routes with the same name will raise an exception at app load time. In the above example, it is important to note that the two routes respond to the same URL but they have two different route names (authenticated_root_path and root_path).