Role based authentication for NodeJS and ExpressJS

Overview

Role based authentication

Authentication service made for ExpressJS and MongoDB using JWT. We tried to make it as clean and structured as possible. We also provide this documentation on how to install and integrate it with your own application.

The code uses MongoDB, in case you are using another database there are few changes that has to be made to the configuration and the routes.

It is also not final and always open for reviews and enhancements, especially when it comes to security

Installation

$ git clone https://github.com/Allin-beta/role-based-auth.git
$ cd role-based-auth
$ npm install

After installing the required packages

  • Browse to .env file and setup your mongo link, Secret and token expiration duration
DB=[mongodb_link]

SECRET=[32_bits_or_more_complex_secret]

TOKEN_EXPIRATION=[token_expiration_time_in_hours]

User:

http://localhost:3000/api/auth/signup http://localhost:3000/api/auth/login

Other roles: {admin, superadmin}

http://localhost:3000/api/auth/signup-[role] http://localhost:3000/api/auth/login-[role]

Structure

  • It is preferred to add new feature folder inside controllers folder
  • It is preferred to add role folder that exports all routes of that custom role
─── Controllers
	└─── auth
	│     └─── register
	│     └─── login
	|     └─── validate
	└─── feature 2 [you can add your own controller]
	└─── feature 3
─── Config
	└─── index.js [it takes configuration from .env]
	└─── roles.js [You add more roles here ]
─── Middlewares
	│
─── Models [It has only User Model]
	│
─── Routes
	│   └─── auth [It has all signup and login routes]
	│   └─── admin [All routes for admin]
	|	└─── [custom role 1]
	|	└─── [custom role 2]
	└─────── index.js [import all routes here]

The route takes 2 functions

  • userAuth from Passport package
  • CheckRole that does the role verification
router.get("/profile", userAuth, checkRole([ROLE.user]), async (req, res) => {
	res.status(200).json({ type: ROLE.user, user: serializeUser(req.user) });
});

Packages

All thanks goes to these packages that made role-based authentication possible.
Mongoose : Object modeling tool for MongoDB
Passport and passport-jwt : Authentication middleware for ExpressJS using strategies plugins like (passport-jwt)
jsonwebtoken : An implementation of JSON Web Tokens
joi: Description language for object schema and data validation
consola: Elegant Console Logger for Node.js
bcryptjs: Password encryption and decription library\

License

Permission is hereby granted to any person to use and edit the code.

You might also like...

A boilerplate for ExpressJs projects configured with ESLint, Prettier & Airbnb Setup. The boilerplate utilises RESTful architecture and uses Mongodb.

A boilerplate for ExpressJs projects configured with ESLint, Prettier & Airbnb Setup. The boilerplate utilises RESTful architecture and uses Mongodb.

ExpressJs-Boilerplate An ExpressJs boilerplate configured with ESLint, Prettier & Airbnb Setup. The boilerplate utilises RESTful architecture and uses

Mar 8, 2023

Simple auth application with ExpressJS.

NodeJS JWT Authentication sample This is a NodeJS API that supports username and password authentication with JWTs. Available APIs User APIs POST /reg

Nov 2, 2022

Authentication system made with NodeJS and MongoDB.

Auth-API A authentication system made with NodeJS. It's a service where you can register your user, then use the credentials to login . What I used in

May 18, 2022

Angular 14 JWT Authentication & Authorization with Web API and HttpOnly Cookie - Token Based Auth, Router, Forms, HttpClient, BootstrapBootstrap

Angular 14 JWT Authentication & Authorization with Web API and HttpOnly Cookie - Token Based Auth, Router, Forms, HttpClient, BootstrapBootstrap

Angular 14 JWT Authentication with Web API and HttpOnly Cookie example Build Angular 14 JWT Authentication & Authorization example with Web Api, HttpO

Dec 26, 2022

CLI Progress Bar implemented in NodeJS to track Time, ETA and Steps for any long running jobs in any loops in JS, NodeJS code

CLI Progress Bar implemented in NodeJS to track Time, ETA and Steps for any long running jobs in any loops in JS, NodeJS code

NodeJS-ProgressBar CLI Progress Bar for NodeJS and JavaScript to track Time, ETA and Steps for any long running jobs in any loops in JS, NodeJS code D

Nov 14, 2022

A CLI tool to create a NodeJS project with TypeScript CTSP is a CLI tool to make easier to start a new NodeJS project and configure Typescript on it.

A CLI tool to create a NodeJS project with TypeScript CTSP is a CLI tool to make easier to start a new NodeJS project and configure Typescript on it.

CTSP- Create TS Project A CLI tool to create a NodeJS project with TypeScript CTSP is a CLI tool to make easier to start a new NodeJS project and conf

Sep 13, 2022

A dead simple JWT-based authentication library for Next.js framework.

nexauth A dead simple JWT-based authentication library for Next.js framework. Getting Started Visit https://betagouv.github.io/nexauth/#/install to ge

Aug 2, 2022

An Opensource Peer-to-peer Social Network with Zero-Knowledge-Proof based authentication.

HexHoot This is an attempt to create an Opensource Peer-to-peer Social Network with Zero-Knowledge-Proof based authentication. The objective is to dem

Dec 28, 2022

This Application provides basic authentication features like you can register and create account and then login and access your profile.

  This Application provides basic authentication features like you can register and create account and then login and access your profile.

Authentication API This Application provides basic authentication features like you can register and create account and then login and access your pro

Jan 17, 2022
Owner
null
To-do-expressJS-api - An ExpressJS API, where you can create your own To-Do's

ExpressJS to-do API What is this API about? This is an API where you can do the following: Log in. Sign up. Create task Read Task Update Task Delete T

Pértile Franco Giuliano 1 Jan 3, 2022
Grupprojekt för kurserna 'Javascript med Ramverk' och 'Agil Utveckling'

JavaScript-med-Ramverk-Laboration-3 Grupprojektet för kurserna Javascript med Ramverk och Agil Utveckling. Utvecklingsguide För information om hur utv

Svante Jonsson IT-Högskolan 3 May 18, 2022
Hemsida för personer i Sverige som kan och vill erbjuda boende till människor på flykt

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

null 4 May 3, 2022
Kurs-repo för kursen Webbserver och Databaser

Webbserver och databaser This repository is meant for CME students to access exercises and codealongs that happen throughout the course. I hope you wi

null 14 Jan 3, 2023
This is a full-stack exercise tracker web application built using the MERN (MongoDB, ExpressJS, ReactJS, NodeJS) stack. You can easily track your exercises with this Full-Stack Web Application.

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

WMouton 2 Dec 25, 2021
@Ifycode's buuk API (nodejs, expressjs, mongodb)

@Ifycode/buuks-express-api Hosted on Heroku: https://buuks-express-api.herokuapp.com "Buuks" instead of "books"... Another angle ?? The API allows an

Obiagba Mary Ifeoma 7 Apr 21, 2022
Displays all hidden Channels, which can't be accessed due to Role Restrictions, this won't allow you to read them (impossible)

Who is the Creator ? The creator of this plugin is DevilBro I have completely reworked the plugin so that it can use the BDFDB library from DevilBro !

Flavien 18 Dec 29, 2022
Displays all hidden Channels, which can't be accessed due to Role Restrictions, this won't allow you to read them (impossible)

ShowHiddenChannels Plugin Returns DevilBro, author of this plugin, and BetterDiscord developers have deleted ShowHiddenChannels plugin from the offici

NotCapengeR 177 Sep 17, 2022
Pim 4 Jun 21, 2022
We are creating a Library that would ensure developers do not reinvent the wheel anymore as far as Authentication is concerned. Developers can easily register and download authentication codes that suits their need at any point.

#AuthWiki Resource Product Documentation Figma Database Schema First Presentation Live Link API Documentation Individual Contributions User Activity U

Zuri Training 17 Dec 2, 2022