Introduction
In this blog we are going to be talking about a simple setup to authenticate your users using sessions. Using sessions allows you to persist the user as they interact with the application.
Getting Started
The first step is to set up your routes in the routes.rb
file. We'll setup two custom routes, one for the login and one for the logout.
The first route will direct a POST
request to the SessionsController
and use the create
action. Here the find_by
method is used to search the database for the user that is attempting to login. If the user is located in the database, that user will then be set as the user that is held in session.
By setting the user in sessions, that user will persist as the current user while they interact with the application. In the following code you can see the create
action that was used to achieve this.
In the above code, you can also see the destroy
action defined. We get to this action using the second custom route from above. In that route we direct a DELETE
request to the SessionsController
and use the destroy
action.
The destroy
action simply deletes the user_id
from session and by doing so the user is no longer persisted so functions that require a user_id
will no longer function.
Frontend
The final step is setting up the front end to actually make the fetch requests for logging in and logging out. First we'll look at logging in.
The login is handled by setting up a form for the user to enter their username
and password
. When they submit the for a function is called that makes a fetch request using the login path and sending the username and password. The response is then handled with an if/else
statement. If the response is ok, then the login process can be completed. If there was a problem with the login, such as the user doesn't exist or the password was incorrect, then an error is returned and can be used to notify the user of the issue.
The final step is to handle the logout when the user is finished using the app.
When the user clicks on the logout button, a function is called which does a fetch request using the logout
route and sending the DELETE
request that will remove the user_id
from session.
Top comments (0)