To build login/sign-up and logout RESTful API’s with node.js using jwt-authentication

Sarthak Mittal
10 min readJul 10, 2020

--

Hello guys, so here we are going to make RESTful API’s for user login/sign-up and logout with node.js, express and MongoDB using jwt(jsonwebtoken) authentication. Since, we know that registering an user in our app is always our primary motive, so to begin with first first of all we have to make our basic server in nodejs.

Requirements for running all these API’s well are fully installed node.js in your system along with MongoDB for database and postman for checking our API’s those who don’t have installed these softwares in their system, please refer to my previous block here

Now to start with first of all check the node version in your system by using command line with below command

node -v

So let’s make our project directory named login-signup-logout api or whatever else. TO begin with we have to first initialize our node.js app by using command

npm init

Then your app will be initialized installing all basic dependencies, here you have to just pass some details if you want otherwise no need but in the package name enter crud or any single word, command prompt will look like this

So now we will going to install some dependencies that will require in developing our api’s like express,body-parser and mongoose, So in terminal write

npm install express body-parser cookie-parser bcrypt mongoose jsonwebtoken nodemon

Use of each module is stated below:

  1. express : Allows you to define routes of your application based on HTTP methods and URLs.
  2. body-parser : It is used to handle HTTP post requests and extract the entire body portion of an incoming request stream and exposes it on req.body.
  3. cookie-parser : It is used for parsing the cookies
  4. bcrypt : It is used for hashing and comparing the passwords.
  5. mongoose : It is used to connect to our MongoDB database.
  6. jwtwebtoken : JSON Web Token (JWT) is an open standard that defines a compact and self-contained way of securely transmitting information between parties as a JSON object.
  7. nodemon : It’s my favorite and it led to automatically restarting of our node application when any changes occur in our app.

So after installing all these dependencies our package.json file will have the name of all these dependencies.

package.json

Now let’s define our app directory i.e. the name of all the folders and files within them, our main file would be index.js that will contain the app listening info.

app directory

Here, config.js will contain the database url along with our secret key for jwt verification, auth.js will contain code for finding the user token, user.js will have user schema and finally our index.js will have all our routes and imported dependencies

So let’s write our basic node.js app in index.js

Here we have required all our basic dependencies also we have used body-parser and cookie-parser as well in our app, app is listening at localhost:3000

Now for running our app just pass one word in your terminal

nodemon

After passing this you don’t have to restarting your server again and again it will do automatically, That’s why nodemon is my favorite as it saves time

Our next task is of defining config.js for using our database and node environment

The benefit of using config.js is that when we deploy our app than our secret key as well as our database will work globally not locally that we are using now.

So next task is to define our user schema

Here, we have added all the basic details that we have needed for registering our user his full name along with his email and password, here you can see 2 passwords that are nothing but password and confirm password, Here I have made all the fields in required category so if any of the filed is sent empty by the user then error will be shown to the user also I have defined the minimum length for the password, so user has to enter the password minimum length of 8, you can change according to your wish.

So let’s connect our app to the database in index.js

here we have to import from config.js file for using the database url for our app and mongoose.connect() function connected our database with our app.

Now in your terminal you can see the line stating that database is connected

Now in user Schema I will define some pre functions which will execute when particular functionality has been called, So our pre function

This function is used for hashing the user password, so when we save our user into the database this function will call itself and hashed our password

This function is included in user.js and we have to require some packages also in user.js file for our next functions also

Add this code at the top of user.js file, here salt is used in hashing

Now let’s define some more functions in user.js as by defining them here we will not have to write them again and again just by calling our problem will be solved.

So next function is for comparing the user password when user tries to login as we have hashed the password so for comparing the password entered by user with our saved password we have to decode the previous one, so code for the same is below:

Here, we have checked whether passwords are same or not.

Next function is for generating a token when user logged in.

generateToken function is used in login route, here we will generate the user token using jwt.sign() function which is used by us for checking whether the particular user has been logged-in or not and we will save this in database

Next method is to find a particular token :

This method is used when we have to find whether a user is logged-in or not

Our next method is for deleting a token, when the user logout we will delete this particular token.

So with this our all function has been defined, now before preceding to the index.js file for defining our basic routes let’s headed towards auth.js file which we will going to use to check whether the user has been logged in pr not.

In auth.js first we will extract the available toke from cookies then we will directly call the findByToken function from user.js and check for the login status of the user.

So we have defined our all functions and utilities for defining our routes, So tit’s the time for our main routes

But before defining the routes we have to import the user model as well as auth.js into our index.js file so paste the below code at the top of the index.js file

Let’s start with the registering user i.e. signup route which will be a post route so add the below code in your index.js

Here, first we will extract all the user info using req.body, first we will check the user’s password and confirm password i.e. password2 if they are not same then error message will be shown to user that password not match, after this we will do one-way authentication by checking the entered email has been found in our database or not, if yes then we will simply send an error message of email exits with error code 400.

if email doesn’t exists which means we are all set to register the user , so when we call newuser.save() function our pre function in user.js will be automatically called and will hash the user password, we are hashing the password on the security reasons as by hashing no 2 password in the databse would be same,after successfully registering the user, a success message will be sent to user with a success code of 200. I am not using 2-way authentication (authenticating using otp verification) here.

Our next task is for user login, for this user has to just pass his email and password and then we will first check for the email whether this email exists or not then we will check the passwords and then we will generate the login token using our predefined function in user.js

Here, firstly we check whether a user is already logged-in or not by using findByToken function, if he is then we will send error message for already logged in.

Afterwards we will check for the email whether it exists or not, if not error will be shown to user, if user exists then we will passwords using comparepassword function from user.js, if everything goes fine then we will generate our login token using predefined function and send success message to user. With this our login route has been completed

Next route is nothing but simply for seeing the user profile by the user which he can only see if he is logged-in, here use of auth.js will come as it will check whether the token exits for particular user or not if yes profile will be shown means currently user has been logged in, so code for the same is

So simply auth has been called and it will chcek for the login status of the user.

Finally our last route is for logout the already logged in user.

Here first auth will do its work for checking the token if token exits then we will delete the token and user has been logged out finally.

So that’s all with these api’s now it’s the time for their testing using postman

First we will check our sign-up api which is

localhost:3000/api/register

First we will check for our empty fields that if user is trying to send some empty fields then what will happen

Yes, error has been shown to the user

Now we will check for password match that what will happen if password and password2 are not same

Passwords not match is shown to the user along with 400 error code

So by passing same passwords and filling up all the fields we will register the user

Yeah, the user has been registered successfully.

But if we try to register some another user with same email then we will see what will happen

Auth failed, same email exists which means our one-way authentication is running well.

It’s the time for checking our login api which is

localhost:3000/api/login

If user passed email that is not in database then error will show

Auth failed, email not found as user has passed wrong email.

Next, if user passed wrong password then

The error message is showing that stated passwords doesn’t match. So user has to provide both the fields correct.

Now if user provide both validated field then

User will be successfully logged in using our API and a token will be generated in the database.

Now if the user again try to login then error message will be shown

Message stating that you are already logged in will be shown to user with 400 error code.

Now we will see the profile of already logged-in user

localhost:3000/api/profile

User’s complete details is shown

Now checking our final api i.e. logout api

localhost:3000/api/logout

For this we have to do nothing but just make a get request and the user will be logged out.

Ok, we have been logged-out, Now let’s verify this by again checking the profile as profile will only be shown to user if he is logged in, if he is logged-out we will not shown anything

So, let’s call our profile api now

Error has been shown which means we have successfully logged-out.

So that’s all with this….

Conclusion

So, in this blog we have learnt how to make user’s api’s for login, sign-up, see profile and logout with node.js, express and mongodb using jwt authentication

I hope you all enjoyed a lot!!!!!

For more information and code-review just see my github repository that has all the code for these RESTful api’s

Thankyou-)

Have a nice day and happy coding!!!!

--

--

Sarthak Mittal

Upcoming SDE @Amazon India, Former UI dev Intern @Siemens India, SIH’20, NIT KKR’22