Great work so far! We’ve built an authentication system that lets new users sign up for the site, and lets existing users log in and out.
However, there’s one problem - even after you log out, you can still access the albums page. Why does this happen? Let’s look at the request/response cycle:
- Currently when a user visits the URL /albums, the browser first makes a request for that URL.
- The request hits the Rails router.
- The router sends the request to the Albums controller’s
indexaction regardless of whether a user is logged in.
What we want instead is for only users who are logged in to see the albums page; otherwise they should be redirected to the login page. This means that we need to check whether a user is logged in before sending her request on to the Albums controller’s
index action. Let’s see how to do this.
In app/controllers/application_controller.rb, add a method named
helper_method :current_user def current_user @current_user ||= User.find(session[:user_id]) if session[:user_id] end
current_user, add another method named
def require_user redirect_to '/login' unless current_user end