MONGOOSE MIDDLEWARES

Login Middlewares for API Authentication

A guide to implementing middleware for Login users in mongoose schemas that Hash the password and checks the user’s credentials(email, password). In this article, we will learn to write middleware for Hashing password and Finding credentials from DB with the custom-defined method.

Punitkumar Harsur
Webtips

--

Firstly, We are creating model cum schema for users details and we need to define the schema for a user who can give fields like Name, Email, password, age and phone. So by using Mongoose is an Object Data Modeling (ODM) library for MongoDB and Node.js.

So What is Mongoose?

Mongoose is an object modelling tool designed to work in an asynchronous environment. Everything in Mongoose starts with a Schema. Each schema maps to a MongoDB collection and defines the shape of the documents within that collection. Mongoose makes it painlessly easy to work with MongoDB database.

We can easily structure our database using Schemas and Models, Automate certain things when the record is added or updated using Middlewares/Hooks and easily get the data we need by querying our models.

Further down the line, we will import the validator package which validates and sanitizes strings only. And bcryptjs package for hashing passwords.

During defining Schema we need to make sure that we create schema and model separately as take advantage of Middleware.

In the figure show userSchema with name, email and so on. The Name has defined with constraints like type,required ,trim which tells that entered name must be String type, and one cannot leave empty for this field and trims the spaces.

user-Schema

Once the schema is created we need to create a model for the user just below schema

user-model

Now we need to convert the passwords that the user is about to enter and save it in the Database. So we can use pre middleware/hook which performs certain logics like performing password hash before saving into DB.

For more understanding on Middlewares of mongoose.

Now comes the implementation of middlewares we will have two one for

  1. Hashing password
  2. Matching user credentials.

NOTE: These middleware must be implemented between schema and model definition.

1. PASSWORD HASHING MIDDLEWARE:

In order to convert the password to hash code, we need to use bcryptjs package.

Password-hash-middleware

Above code is self-explanatory, this the keyword will point to current user document. Here we need to make sure that password needs to hash only once and Should create a new password hash for new user and during modifying on a user password. So, modified() is taken into if clause.

Hash() is await and synchronous function which takes 2 argument password and number of rounds to hash algorithm must execute. 8 rounds are most recommended as it gives a balance between security and speed.

next argument: The whole point of this is to run some code before (a user is) saved. But how does it know when we’re done running our code. Now it could just say when the function is over. But that wouldn’t account for any asynchronous process which might be occurring. So that’s why next is provided. We simply call next when we’re done.

Note: if we never call next. It’s just going to hang forever. Thinking that we’re still running some code before we save the user and it will never actually save the user.

2. MATCHING USER CREDENTIALS :

Here we defining custom method findByCredentials() which takes email and passwords form req.body. We can implement this custom function in 2 parts

  1. Finding User by Email Match.
  2. Finding User by Password Match.
Matching-Credentials-function

so we will take the user by his email as store in user a variable which can be returned on successfully matching with email and password.

compare() is async and await function which takes a password and hashed password and on compare returns a boolean value.

Signup-endpoint

Once the reusable custom function is implemented we can use the above-defined reusable function findByCredentials() in endpoints.

--

--

Punitkumar Harsur
Webtips

Data science SME. Hustler, Content creator, Photography Enthusiast. LinkedIn: www.linkedin.com/in/punityh