Learn
Authentication
current_user

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.

Instructions

1.

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

Below current_user, add another method named require_user:

def require_user redirect_to '/login' unless current_user end
Folder Icon

Sign up to start coding

Already have an account?