How to Sign In with raw password when password store in the database are hashed form in Node.js ?
The password stored in the database is always in (hashed+salt) form because of security reasons. When users sign up on any website, a password is given in the raw form. But storing the raw passwords in the database directly is not a good practice. Using some server-side logic we first convert raw passwords in the (hashed+salt) form then store it in the database. This arises a new challenge, how to compare the raw password given by the user at Sign In time and give access to the user on the basis of the password is correct or not.
Password stored in the database in the following form:
Steps to set up logic to Sign In with raw password:
- Search the database with the help of unique username or email given by the user to sign in.
- Find the unique record and if not found return ‘User not exist’.
- Split the encrypted password at ‘ . ‘ to find the hashed password and salt individually.
- Hashed the raw password given by the user to sign in with Node.js ‘scrypt’ method using salt.
- Compare the obtained hashed with the hashed got from splitting the database password.
- If both hashed are equal signed in the user and give the access.
- If both hashed not equal denied the access with message Invalid password.
Note: To illustrates the logic, here we take a local or custom database. same logic can also be implemented with the regular database like MongoDB, MySql etc.
Example: This example illustrates how to sign in with a raw password when stored password in the database is in (hashed + salt) form.
Filename: repository.js This file contains all the logic related to create a local database and how to interact with it.
Run index.js file using the following command:
Here we submit three forms individually with a different combinations of username and password and get the output as shown in the image respectively.