In the previous part we saw how to build the signup page. In this part we will create sessions and persist our user object in the session. To start this, we will create a controller to handle the sessions.
Modify the routes to create resources for the sessions controller.
In sessions controller, we will modify our actions to check the user by user_name. In case you want, you can change it to email or both. Rails does some more magic behind the scenes using the user.authenticate(params[:password]). has_secure_password generates the salt and allows us to use .authenticate method which matches the salted password with the params passed. Also, we will persist the user_id in the session. In order to create a logout, we will simply set the session’s user_id to nil.
Our login form will look like the following and will be accessible at sessions/new.
We will also create a separate route for logout.
We will create a blank controller where we can redirect the page after the session is created.
Now, to access the persisted user as an object in the session we will create a current_user method. Through this we can access the user’s details when the he or she is in the session.
We also need a filter method to protect our methods that we need to keep only for the logged in Users. In order to do that, we will create a method called authenticate_user. This method will check the presence of user_id and accordingly redirect to the respective page.
We can now put our dashboard behind the login.
Also, we can use current_user object to show conditional login and logout links and also show the details of the session user.
So, we have successfully created sessions, made method to protect actions and also persist the user in the session.