Node.js Authentication with PostgreSQL, Sequelize, and Express.js
Using JSON Web Token( JWT ) and Cookie-Parser for User Authentication
In this article, we are going to discuss user registration and login by setting cookies with Cookie-Parser and JSON Web Token(JWT) using PostgreSQL as the database with Sequelize as Object Relational Mapper(ORM) and Express.js for the server.
Understanding the Concepts
User registration is one of the relevant steps in an application, thus the concept of authentication and authorization. Authentication and Authorization are requirements for security purposes.
These two concepts are often used interchangeably which becomes difficult to differentiate the feature you want to implement and what it requires.
Before we dive into authentication, let’s clarify the difference between these two concepts. Authentication is determining if a user is who they claim to be. With this, it checks the database to see if the user’s credentials match the ones in the database of an authorized user. In contrast, authorization specifies data users can get access to in your application.
Cookies are small pieces of data that are sent to the web browser in a request. They are stored in the web browser as key-value pairs. The key serves as the name given to the specific cookie. The value represents the specific data that is required. Cookies are essential in most applications. For example, cookies can keep users logged in to your application. For this application, we will use Cookie-Parser and JSON Web Token to generate a token to be used as the value for the cookie.
example of a cookie — admin: ydfgyfgeuygfegyfgirgcfygfyhgcyg
JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compact and self-contained way of securing and transmitting information between parties as JSON objects. JWT consists of three parts separated by dots which are the header, payload, and signature. The payload feature which allows us to use the user id with a secret key to generate a token makes it more relevant to use it to set a cookie for a particular user.
Table of Contents
- Step 1: Create node express project
- Step 2: Database and server configuration
- Step 3: Set up user schema
- Step 4: Middleware setup
- Step 5: Set up an environment variable
- Step 6: Set up controllers
- Step 7: Configure an express router
- Step 8: Refactor the server
- Step 9: Testing
Pre-requisites
First, you must have these installed
Node => https://nodejs.org/en/download/
PostgreSQL & pgAdmin => https://www.enterprisedb.com/downloads/postgres-postgresql-downloads
Step 1: Create Node Express Project
Create a project folder by the following command
mkdir backend
cd backend
Now, create a package.json file using the following command
npm init -y
NB: sequelize documentation for reference => https://sequelize.org/docs/v6/getting-started/
Next, Install these packages
- Express — Node.js framework
npm install express
- Sequelize — object-relational mapper for PostgreSQL
npm install --save sequelize
- Pg and pg-hstore — pg is a PostgreSQL client for Node.js and pg-hstore is a node package for serializing and deserializing JSON data to hstore format —
npm install --save pg pg-hstore
- Nodemon — Automatic restart of node application when file changes are detected —
npm install –save-dev
- Bcrypt — For password hashing =>
npm install bcrypt
- Dotenv =>For access to your environment variable =>
npm install dotenv
- JSON Web Token => For generating tokens =>
npm install jsonwebtoken
- CookieParser => For setting cookies =>
npm install cookie-parser
Once you are done with the installations, create a server.js file and change your package.json file by adding a start to the scripts like this.
Step 2: Database and Server Configuration
In the server.js file, import your modules, set up your port, and listen to the server connection.
Server.js
Next is creating your folder structure with Model Views Controller ( MVC ) Approach
- Controllers
- Models
- Routes
- Middlewares
Database Configuration
In your Models folder create an index.js file and set up your database with Sequelize ORM.
But before this, open your pgAdmin and create your database.
const sequelize = new Sequelize('postgres://user:pass@example.com:5432/dbname') // Example for postgres database connection
Model/index.js
Step 3: Set up your User Schema
Once your database is set up, create another file in the Model folder, userModel.js to set up your user schema with Sequelize.
Model/userModel.js
Step 4: Create your Middleware
Middleware
The next step is to create a function that checks for existing usernames and emails in the database to avoid duplicates before saving a user. Create a userAuth.js file in the middleware folder.
Middleware/userAuth.js
Step 5: Set up your Environment Variables
The .env file is used to store secret keys. Create a .env file in your root folder and save random letters in a variable.
Eg. secretKey = ydwygyegyegcveyvcyegc
Step 6: Set up Controllers
The controller contains the logic to register the user to our database and login. Create a userController.js file. There are two main functions in the controller which are :
signup: creates a new User by hashing the password with bcrypt before it’s saved in the database
login :
- find the email of the request in the database, if exist
- compares the password with the existing password in the database if it matches,
- generate a token with the user id using ( JWT ) and set a cookie with Cookie-Parser for the user
- return user information
Controllers/userController.js
Step 7: Configure Express Router
In the routes folder, set up the routes for the application by using the Router module provided by Express.js. So create a file in the routes folder called userRoutes.js. In the signup route, the middleware is passed to check for duplicates of usernames and emails in the database.
Routes/userRoutes.js
Step 8: Refactor the Server Code
Your final server.js after importing the routes and database module should look like this
Server.js
Step 9: Testing
Time to test your endpoint with Postman or REST Client.
Open up your terminal and run,
npm start
Signup API
http://localhost:8080/api/users/signup
Login API
http://localhost:8080/api/users/login
Conclusion
Congratulations!
You have successfully completed User Authentication with Sequelize ( ORM ), PostgreSQL, and Express.
CHEERS!!!