Rails Auth Part 2

Adam Chernitsky
3 min readMar 27, 2020

In my last blog I started to build user controllers and models. In this blog I will show you how to implement your login method so preexisting users can sign in. This blog will build off of the last so if you’re not up to speed please read my last blog.

To start out we are going to create a new controller where our login method will be:

Before we start building our login method we have to go our routes.rb file in the config folder. In here we have to add some code:

Now our route is set up for our login method. Next we are gonna start to build our login method but in order to do this there is a gem we need to add to our gemfile. To do this run this command in your terminal:

Now that we have our JWT gem we can build our login method in our authentication controller:

This method is pretty meaty so I’ll do a quick breakdown, what we’re doing in this method is looking up a user by that users username. If the username matches we are going to authenticate them with their password and if that matches then they will have successfully logged in, if not they will get an error message and a status unauthorized.

Now that we have our login method we need to go test that it is working in Postman. To do this create a user or use a preexisting user, you will make a post request to localhost:3000/login. First we need to start our rails server so we can test in Postman:

Now in Postman we can test our login method:

Make sure the username and password match a preexisting user, or create a new one and use the same data.

If done successfully you should get a token:

If done unsuccessfully:

You get a 401 unauthorized as well as the message you chose to send, mine being “Incorrect”, now we have a login method that can look up usernames and verify their passwords. Now you can have users in your app. In the next auth blog we will discuss protecting your other routes and resources.

--

--