User Authentication in Sinatra

Muhammad Musah
3 min readSep 13, 2020

When making a web application, user authentication is one of the most essential aspects of development. User authentication is the process of proving the identity of a user in order to allow access to other parts of the app. in this blog I will go over some of the aspects of setting up authentication for a Sinatra app.

For the case of this app there will be a username and password that needs to be validated. Other apps may use attributes like email or birthday for validation. The first thing that needs to be done in our User model is add our validations to make sure that the presence and uniqueness of a username is secured in each column.

Then we need to enable a ruby gem called ‘bcrypt’ which allows us to set up the password authentication and use has_secure_password as seen above in our User model. This will allow us to use .authenticate when setting up our log-in in our User controller.

In the User controller below, we set up the logic for what happens when we submit our form to log in to an account. We first set the “user” variable in order to find the username that is submitted to the params hash. The next line is a conditional that assigns the session to the user’s user_id, then redirects us to the homepage if the username and the password that is entered is valid and exists.

The .authenticate method comes from the bcrypt gem. This matches the password that was entered into the params hash to the salted password that was already saved in the database into the database during sign-up. If the password or username don’t match, we’ll be re-directed to the sign-up page along with a flash error.

It is very important to have a secure app in order to prevent mischievous people from toying with users’ private accounts. In this blog we went over how we use BCrypt, ActiveRecord methods, and our user controller in order to set up a safe and sound user authentication in Sinatra.

--

--