The most common techniques for implementing sessions in trainjs involve using cookies, which are small pieces of text placed on the user’s browser. Because cookies persist from one page to the next, they can store information (such as a user id) that can be used by the application to retrieve the logged-in user from the database. In this section and “Logging in” Section, we’ll use the session to make temporary sessions that expire automatically on browser close, and then in “Remember me” Section we’ll add longer-lived sessions using another the module called cookies.
Sessions controller
The elements of logging in and out correspond to particular REST actions of the Sessions controller: the login form is handled by the new action, actually logging in is handled by sending a POST request to the create action, and logging out is handled by sending a DELETE request to the destroy action.
Unlike the Users resource, which used the special resources method to obtain a full suite of RESTful routes automatically, the Sessions resource will use only named routes, handling POST request with the login route and DELETE request with the logout route.
config/routes.js
Change
to
Login form
With the proper form_for in hand, it’s easy to make a login form.
public/partials/sessions/new.html
public/controllers/sessions_controller.js
Finding and authenticating a user
Inside the create action the req.body has all the information needed to authenticate users by email and password. Not coincidentally, we already have exactly the methods we need: the User.find method and the authenticate method.
app/controllers/sessions_controller.js
Rendering with a flash message
Recall from “Unsuccessful signups” Section that we displayed signup errors using the User model error messages. These errors are associated with a particular Sequelize object, but this strategy won’t work here because the session isn’t an Sequelize model. Instead, we’ll put a message in the flash to be displayed upon failed login.
app/controllers/sessions_controller.js
public/controllers/sessions_controller.js
public/helpers/flash_helper.js
A failed login test
We start by generating an integration test for our application’s login behavior