Skip to content

How To: Require authentication for all pages

Garrett George edited this page Mar 16, 2021 · 8 revisions

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:

# config/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 the following might suit well in such case:

# config/routes.rb

...

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

Clone this wiki locally