Authentication

If you haven't already, first read the previous post about Users.

The basic authentication scheme that we'll use depends on a unique identifier (an email) and a secret value (a password). We will check that a user knows the exact combination of these two credentials, thus "authenticating" that user into the app.

It's worth noting that there are many other authentication schemes:

  • Log in with Google (or GitHub, or LinkedIn): the app sends you to another service, lets you log in there, and trusts its answer. This is OAuth.
  • A code by text, email or an authenticator app, on top of the password: multi-factor authentication (MFA, or 2FA).
  • A magic link: no password at all, just a link emailed to you that logs you in once.
  • Single sign-on: your company's login, used for every tool at work.
  • Passkeys: your phone or laptop proves it's you, with your face or fingerprint, and there's no password to steal.

There are tradeoffs to using any scheme. For example, more security often means more friction for the user, and logging in with someone else's service means sharing data with them. So you need to find an appropriate balance in your application.

The routes

The period of time when a user is logged in is commonly referred to as a "session". A session isn't database-backed - there's no sessions table - so this is one of the rare places where we break the pattern on purpose. Open config/routes.rb and look at the bottom:

get("/login", { :controller => "sessions", :action => "new" })
post("/login", { :controller => "sessions", :action => "create" })
get("/logout", { :controller => "sessions", :action => "destroy" })

Three routes, written out by hand instead of a resources line, because there's nothing to list, show or edit, and /login reads better than /sessions/new. Each one still goes to a controller and an action, just like the seven routes a resources line makes.

The login form

Click Log in in the navbar. The new action in app/controllers/sessions_controller.rb renders app/views/sessions/new.html.erb:

<h1>Log in</h1>

<form action="/login" method="post">
  <p>
    <label for="email">Email</label>
    <input type="text" name="email" id="email">
  </p>
  <p>
    <label for="password">Password</label>
    <input type="password" name="password" id="password">
  </p>
  <button>Log in</button>
</form>

The form makes a POST request to /login, and the second route above sends that to the create action. Try logging in as ben@example.com with the password tacos123. You get "Nope." no matter what you type, because create doesn't do anything yet:

def create
  # 1. find the User whose email was typed in the form
  # 2. check the password
  # 3. if both hold, put the user's id in the session, then redirect to the posts
  # 4. otherwise redirect back to the login form
  flash["notice"] = "Nope."
  redirect_to("/login")
end

In other resources, create is where we would use the model to insert a row into the table. That doesn't make sense for a session. Instead, we check the form data against the data in the users table, and if it matches, log the user in. Let's fill in the comments.

Step 1: find the user

Since email is a unique identifier, we can use it to find a row in the users table. Look at the server log for the request you just made and you'll see the form's data in the params: "email" => "ben@example.com". It's at params["email"].

# 1. find the User whose email was typed in the form
user = User.find_by({ "email" => params["email"] })

Submit the form again and watch the log. You'll see the request, and then the SQL query for a user with that email:

SELECT "users".* FROM "users" WHERE "users"."email" = ? LIMIT ?

Notice the ?. Keep it in mind; we'll come back to why it's there when we talk about injection.

Step 2: check the password

If there is a user with that email, we compare the password they typed with the password in the row. find_by returns nil when there's no match, so we check for a user first:

# 2. check the password
if user && user["password"] == params["password"]

Steps 3 and 4: let them in, or don't

If both hold, the user is who they say they are. We remember that, then send them to the posts. Otherwise, back to the form:

def create
  # 1. find the User whose email was typed in the form
  user = User.find_by({ "email" => params["email"] })
  # 2. check the password
  if user && user["password"] == params["password"]
    # 3. if both hold, put the user's id in the session, then redirect to the posts
    session["user_id"] = user["id"]
    flash["notice"] = "Welcome back, #{user["first_name"]}."
    redirect_to("/posts")
  else
    # 4. otherwise redirect back to the login form
    flash["notice"] = "Nope."
    redirect_to("/login")
  end
end

Test it out with correct and incorrect data. Log in as Ben and you land on the posts with "Welcome back, Ben." and his name in the navbar. Get the password wrong and you're back at the form.

session["user_id"] = user["id"] is the line that actually logs the user in. It's the same line the sign-up action ends with, which is how signing up logs you in too. How it works is a post of its own (Cookies). Log out in the navbar runs
sessions#destroy, which sets it back to nil.

If you fell behind, code-along-complete/1-login/ in your copy has this file finished.

One message, on purpose

Notice that a wrong email and a wrong password get the same message: "Nope." It would be friendlier to say "We don't have an account with that email" - and it would also tell anyone who types an email into your login form whether that person has an account. Sometimes that's a secret worth keeping (a dating app, a health app), sometimes it isn't. It's a product decision, and like most security decisions it's a tradeoff between convenience and safety.

Flash

How did that message display on the next page? Look at the layout that wraps every view, app/views/layouts/application.html.erb:

<% if flash["notice"] %>
  <p><em><%= flash["notice"] %></em></p>
<% end %>

That's the notice key in the flash hash. When it has a value (because it was assigned in create before redirecting), the value is displayed. The message only appears on the very next request - refresh, and it's gone. Any HTML that we want displayed on every page belongs in this layout file, like the navbar.

It's understandable if you're confused about how this works - it appears to break the "HTTP is stateless" rule, since the message shows up on the request after the form submission. Spoiler alert: the same tool that carries this message is what remembers that a user is logged in.

But before we get there, there's a problem. Our login checks the password by comparing it with the password in the table, which means the password is sitting in the table, in plain text. Let's shore up some security vulnerabilities in our code first (next post).