Node Authentication: A Simple Guide ๐Ÿ”‘

Node Authentication: A Simple Guide ๐Ÿ”‘

ยท

6 min read

Welcome, fellow developers! Today, we'll explore the exciting world of Node.js authentication. ๐Ÿš€

What is Node Authentication? ๐Ÿค”

Node.js authentication is like a bouncer that decides who gets into a super-secret clubhouse. In the digital realm, it controls access to certain routes or resources in Node.js applications. ๐Ÿ 

How Does it Work? ๐Ÿ’ก

Node.js authentication relies on access control to determine if a user has permission to perform certain actions. This is managed through roles and permissions. ๐Ÿ”“

Introduction

In modern web development, user authentication is a crucial aspect of building secure applications. Node.js, a powerful server-side runtime, offers numerous packages to handle authentication tasks efficiently. In this tutorial, we will explore how to use the Validator and Bcrypt libraries to implement robust user authentication in a Node.js application. Validator will help us validate user input, while Bcrypt will enable us to securely hash and store passwords in our database.

Prerequisites

Before we get started, make sure you have Node.js and npm (Node Package Manager) installed on your system. Additionally, you should have a basic understanding of JavaScript and Node.js, you should also have MongoDB setup on your machine.

Step 1: Setting Up a New Node.js Project

Let's begin by setting up a new Node.js project. Open your terminal and create a new project directory. Navigate to the newly created directory and initialize a new Node.js project using the following commands:

Step 2: Installing Dependencies

Next, we need to install the necessary packages: Express (for building the web server), Mongoose (for MongoDB connection.), Validator (for input validation), dotenv (for local environment setup), Node and Ndemon (Nodemon to continuously run the server.js), and Bcrypt (for password hashing). Run the following command to install them:

With this no we need to set up our .env file and add:

  1. PORT : The port on which we want our server to work.

  2. MONG_URI : The MongoDB database link to store the data.

Step 3: Setting Up the Express Server

Now, let's create an Express server to handle user registration and login routes. Create a file named server.js and add the following code:

Step 4: Starting with the Schema

This is the main part of our project. In this, we make a Schema of credentials that we need to make our application. For us, it is Email and Password.

Once this is done, we now make 2 functions:

  1. Signup

  2. Login

In this, for the signup I have used the validator library for different errors like the "Email is not valid", "Password is not a strong password", and the main "Email is already in use" as we cannot signup two or more users via the same email address.

Now, I used functions like genSalt and hash. The genSalt(10) adds 10 characters before and after the password is entered to encrypt the password. Once the password is encrypted, the user credentials are entered and a user detail is stored.

Coming to the log-in part, I have used the validator library for different errors like the "Incorrect Email" if the email entered is not present in the database, and the "Incorrect password".

We use the match function to compare the password of the user. After this, we use the module.exports to export the Schema.

Step 5: Controllers At Work

Controllers act as intermediaries between the user interface (usually the frontend) and the database (usually the backend). Their primary purpose is to handle and process incoming requests from the user interface, determine the appropriate actions to be taken based on the request, interact with the database to perform the necessary CRUD operations, and return the appropriate response to the user interface.

In this, I used "jwt" i.e. "jsonwebtoken" to generate a different token for different email ids. We create a token using the database id and jwt, we also use a SECRET environmental constant with jwt and we set the signed-up email id to be expired from the database in 3 days.

Now, we make controllers for login and signup using Email and Password and then we can create a token and output the Email and the token in both cases.

In the end, we export it.

Step 6: Routes to the rescue

Routes help maintain a clean and organized structure within the application by specifying the relationship between URLs and the associated actions that should be performed when users access those URLs. Each route typically consists of two main components:

  1. HTTP Method: This indicates the type of request the route is designed to handle. Common HTTP methods used in CRUD applications are:

    • GET: Used for reading or retrieving data.

    • POST: Used for creating new data.

    • PUT or PATCH: Used for updating existing data.

    • DELETE: Used for deleting data.

  2. URL/Endpoint: This is the specific URL or endpoint that users can access to perform a particular action. For example:

    • /users - A GET request to this URL might retrieve a list of users.

    • /users/:id - A GET request to this URL with a specific user ID might retrieve details of a particular user.

    • /users/new - A GET request to this URL might display a form to create a new user.

    • /users/:id/edit - A GET request to this URL with a specific user ID might display a form to edit that user's information.

    • /users - A POST request to this URL might create a new user.

    • /users/:id - A PUT or PATCH request to this URL with a specific user ID might update that user's information.

    • /users/:id - A DELETE request to this URL with a specific user ID might delete that user.

In this, to begin with, imported both loginUser and SignupUser from the controller that we just made above. Now, we initialize the constant router using express.Router().

After that, we now use post requests to add the user credentials via both signup and login requests.

Step 7: Back to the server.js

Now we input the route file to our server.js and add a directory to the routes.

Here, the directory is /api/user.

Now we will start our node project.

And yes it is working.

Step 8: Postman with the Posts

Now, I added my email address to the database using the signup and also logged in via login. I also checked for the errors that we might get.

This is how the credentials are stored in the DB, Password is encrypted.

Now, that's it for this blog. I hope you all enjoyed it, see you in the next one.

Conclusion

Congratulations! You have successfully implemented user registration and login functionalities using Validator and Bcrypt in your Node.js application. By validating user input and securely hashing passwords, you have taken significant steps towards building a secure and robust authentication system.

Remember that user authentication is a critical aspect of any application, and there are many other factors to consider, such as session management and password recovery. Always stay updated with the latest best practices and security standards to ensure the safety of your users' data. Happy coding!

Follow me on Twitter: https://twitter.com/KyaYaaarDhyan

For the source code: https://github.com/DhyanShah22/Auth-Blog

Did you find this article valuable?

Support Dhyan Tech!! by becoming a sponsor. Any amount is appreciated!

ย