Ruby On Rails Lesson
We’re now in a position to start implementing our signin model, namely, remembering user signin status ‘‘forever’’ and clearing the session only when the user explicitly signs out. The signin functions themselves will end up crossing the traditional Model-ViewController lines; in particular, several signin functions will need to be available in both controllers and views. You may recall from Section 4.2.5 that Ruby provides a module facility for packaging functions together and including them in multiple places, and that’s the plan for the authentication functions. We could make an entirely new module for authentication, but the Sessions controller already comes equipped with a module, namely, SessionsHelper. Moreover, such helpers are automatically included in Rails views, so all we need to do to use the Sessions helper functions in controllers is to include the module into the Application controller (Listing 8.14).
By default, all the helpers are available in the views but not in the controllers. We need the methods from the Sessions helper in both places, so we have to include it explicitly.
Because HTTP is a stateless protocol, web applications requiring user signin must implement a way to track each user’s progress from page to page. One technique for maintaining the user signin status is to use a traditional Rails session (via the special session function) to store a remember token equal to the user’s id:
This session object makes the user id available from page to page by storing it in a cookie that expires upon browser close. On each page, the application could simply call
to retrieve the user. Because of the way Rails handles sessions, this process is secure; if a malicious user tries to spoof the user id, Rails will detect a mismatch based on a special session id generated for each session.
For our application’s design choice, which involves persistent sessions—that is, signin status that lasts even after browser close—we need to use a permanent identifier for the signed-in user. To accomplish this, we’ll generate a unique, secure remember token for each user and store it as a permanent cookie rather than one that expires on browser close.
The remember token needs to be associated with a user and stored for future use, so we’ll add it as an attribute to the User model as shown in Figure 8.8. We start with a small addition to the User model specs (Listing 8.15).