If you haven't already, first read the previous post about Encryption & Data Security.
You may already be aware of browser cookies - clearing a website's cookies is often a recommendation when a website isn't working properly. But what does that really mean?
Cookies are made of key-value pairs, or, in Ruby parlance, a Hash. This hash of data is stored in the browser. Since it lives in the user's browser, it's specific to the user and to the website. And here's the important part: the browser sends a website's cookies back to it with every request. HTTP is stateless, but cookies let a website create a sense of state - a memory that lasts from one request to the next.
The flash message from the login is using this tool. When we assign a value to the flash hash, Rails stores it in a cookie for exactly one request: it's read on the very next request and then it's gone. That's how the message appears after the redirect and never again.
When it comes to users, we want to remember who the logged-in user is. We'll call this user the "current user". Cookies are the perfect tool for this - when a user successfully authenticates, we store something that identifies them in a cookie, and then check for it on each new request. If it's there, we know who's logged in. If it isn't, nobody is.
The cookie jar
Log in as a user you created. Then let's look at the cookies in the browser.
In Chrome, go to the View menu, then Developer, then Developer Tools. Chrome has many tools that are incredibly useful for web development. In the panel that opens, choose the Application tab. On the left, find Cookies and open it, then click the address that matches your address bar. Those are the cookies this browser holds for this website.
You'll see one called _starter_app_session, with a long, unreadable value. That's the session, and our user is in there. But you can't tell.
Why not just a cookie?
To see why it's unreadable, let's do it the obvious way first. In sessions#create (app/controllers/sessions_controller.rb), find the line that logs the user in:
session["user_id"] = user["id"]
and add a plain cookie right below it, for now:
cookies["user_id"] = user["id"]
Log out, log in again, and look at the cookies. There's a new user_id cookie, and its value is your id, in plain sight: 3, or whatever your row's id is. On every request from now on, the browser tells our app who the current user is.
Before we go any further, there's a security vulnerability here. Double-click that value in the developer tools. You can change it to anything you want. If you were "logged in" as user 3, maybe you'd like to be user 1. If our app trusted this cookie, by changing that number you'd be logged in as someone else entirely. Imagine being logged in to Amazon and seeing your orders. Change one number, and now you're seeing someone else's orders. Not good.
Delete the cookies["user_id"] line you added, then delete the user_id cookie in the developer tools (right click, Delete).
The session
That's why we use session instead. The session is a cookie too, but Rails encrypts and signs it with a secret only the server knows. You can't read what's in it, and if you change a single character, Rails throws the whole thing out and treats you as logged out. The browser carries it; only the server can open it.
So session["user_id"] = user["id"] is the line that logs a user in. It's in sessions#create, and it's also at the end of users#create, which is why signing up logs you in. Logging out, sessions#destroy, empties it:
def destroy
# empty the session, then redirect
session["user_id"] = nil
flash["notice"] = "Goodbye."
redirect_to("/posts")
end
Current user
Putting the id in the session is half of it. On each request, we need to turn that id back into a user. Open the application controller (app/controllers/application_controller.rb):
class ApplicationController < ActionController::Base
# Runs before every action in every controller.
before_action :find_current_user
def find_current_user
# the session is a small, signed box that travels with the browser as a cookie;
# logging in puts the user's id in it, logging out empties it
@current_user = User.find_by({ "id" => session["user_id"] })
end
end
Every controller in our app inherits from this one (look at the first line of posts_controller.rb: class PostsController < ApplicationController). And before_action tells Rails to run find_current_user before every action, in every controller. So on every request, the app reads the user's id out of the session and looks up their row. If nobody is logged in, session["user_id"] is nil, nothing is found, and @current_user is nil.
Because @current_user starts with @, every view can use it, including the layout. Look at the navbar in app/views/layouts/application.html.erb:
<nav>
<a href="/">Home</a> |
<a href="/posts">Tacostagram</a> |
<% if @current_user %>
<a href="/users/<%= @current_user["id"] %>"><%= @current_user["first_name"] %></a> |
<a href="/logout">Log out</a>
<% else %>
<a href="/users/new">Sign up</a> |
<a href="/login">Log in</a>
<% end %>
</nav>
Logged in, you see your name and Log out. Logged out, you see Sign up and Log in. Click around - the feed, a company, the data page - and your name stays in the navbar on every page, request after request. We can now, at long last, consider the current user as being logged in!
That if @current_user is also our first bit of authorization: the app shows a logged-in user something different than a visitor. Now that we know who the current user is, we can decide what they're allowed to do (next post).