Rails Auth Pt. 1

Adam Chernitsky
4 min readMar 22, 2020

In this blog I’m going to show you how to build the beginning of an app with Auth in it. First things first, we’re going to have to make a new Rails app:

Once your app is finished building and installing open your project in your text editor and we’ll begin creating users. To do this we are going to create a user controller and model:

This command will create your controller, your model, and your migration file for you as well. Next we can start doing some work in the files that we just made. To start we’ll go into our models file and select user.rb. In this file we are going to add a line of code that is for auth:

Next we want to open up our db folder and go into user migration file, in this file we will add our desired user attributes.

In this example I’m just going to use a password and a username. Notice that in the migration file password is password_digest, make sure that yours is the same otherwise you’ll run into errors. Also note that this is the only place that password will be referred to as password_digest. Now that we have our migration file set up go ahead and run our migrations file:

Next we can get ready to start building our methods (or actions) that will go into our user controller. Before we do this though we are going to open our routes.rb file that is in the config folder and make it so the only method that can be used for this class is create:

If you’d like to have other methods for your users feel free to allow their use here. Next we’ll go into our user controller and build our create method:

Notice how password here is just password and not password_digest. Once this is done we only have a few more steps until we can successfully create a user that has a hashed password. We’ll need to go and uncomment a few things from our gemfile next. The main thing you’ll need is bcrypt, the other thing I like to do out of habbit is cors:

Once you uncomment these gems you will need to bundle install:

Once this is done you can start your server:

Now go to Postman and test out your create method. To do so do a post request on http://localhost:3000/users:

Before you hit send in postman make sure you properly create your new user:

Once you have all this done hit send and if you did everything correctly you should get your new user returned to you in the Postman console. However you may notice something strange:

Instead of your password being returned, password_digest is returned with a hashed password. Now you password is secure. In the next auth blog we will build a route to login in a preexisting user.

--

--