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:

  1. Currently when a user visits the URL /albums, the browser first makes a request for that URL.
  2. The request hits the Rails router.
  3. The router sends the request to the Albums controller’s index action 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 current_user

helper_method :current_user def current_user @current_user ||= User.find(session[:user_id]) if session[:user_id] end

Below current_user, add another method named require_user:

def require_user redirect_to '/login' unless current_user end

Sign up to start coding

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?