Now that users can sign up for a new account, let’s add the ability to log in and log out of the app. Using the request/response cycle as a guide again, here’s how logging in and logging out fits in.
Turn one:
- When the user visit the login page, the browser makes a GET request for the URL
/login
. - The Rails router maps the URL
/login
to the Sessions controller’snew
action. Thenew
action handles the request and passes it on to the view. - The view displays the login form.
Turn two:
- When the user fills in and submits the form, the browser sends the data via a POST request to the app.
- The router maps the request to the Sessions controller’s
create
action. - The
create
action verifies that the user exists in the database. If the user exists, thecreate
action logs the user in by creating a new session. Otherwise, it reloads the login page.
Instructions
Let’s begin by adding a login page. Looking at the request/response cycle, we need five parts to add login machinery to the app: a model, a controller, routes, views, and logic for sessions. As we already created the User model when building the signup page, let’s start here by creating a controller.
Generate a controller named Sessions.
In the routes file, create a route that maps requests for the URL ‘/login’ to the Sessions controller’s new
action.
In the Sessions controller, add the new
action
def new end
Then in app/views/sessions/new.html.erb, on line 7, use form_for
to create a login form:
<%= form_for(:session, url: login_path) do |f| %> <%= f.email_field :email, :placeholder => "Email" %> <%= f.password_field :password, :placeholder => "Password" %> <%= f.submit "Log in", class: "btn-submit" %> <% end %>
We’ve also provided CSS in app/assets/css/application.css.
Restart the Rails server and visit http://localhost:8000/login
in the browser.
The form won’t work just yet. We’ll finish it up next.