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
{ res.status(200).json({ type: ROLE.user, user: serializeUser(req.user) }); }); ">
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...

An authorization library that supports access control models like ACL, RBAC, ABAC in Node.js and Browser

An authorization library that supports access control models like ACL, RBAC, ABAC in Node.js and Browser

Node-Casbin News: still worry about how to write the correct node-casbin policy? Casbin online editor is coming to help! node-casbin is a powerful and

Dec 27, 2022

Authenticated server-side rendering with Nuxt 3 and Firebase 9

Authenticated server-side rendering with Nuxt 3 and Firebase 9.

Dec 23, 2022

Role based authentication for NodeJS and ExpressJS

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.

Oct 3, 2021

Automatic Role Adder Is Usually Used In Coding Servers Which Give Access To Codes By Subbing To Their Channel So This Helps Them To Auto Role People :)

Automatic Role Adder Setup Guide Automatic Role Adder Is Usually Used In Coding Servers Which Give Access To Codes By Subbing To Their Channel So This

Dec 23, 2022

To-do-expressJS-api - An ExpressJS API, where you can create your own To-Do's

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

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

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

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

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

Dec 25, 2021

Hotel Booking System Built In MERN (MongoDB, ExpressJs, ReactJs, Nodejs) Stack.

Setting Up The Project Please Run The Commands Below to Run the Project git clone https://github.com/yishakdotjs/yishakdotjs-Hotel-Booking-System-Fron

Feb 3, 2022

@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

Apr 21, 2022

This package allows you to use Okta as your identity provider for use with Netlify's Role-based access control with JWT.

netlify-okta-auth This package allows you to use Okta as your identity provider for use with Netlify's Role-based access control with JWT. Who is this

Sep 17, 2022

Discord Role Guard Backup Bot

Bot Ne Zaman Paylaşılacak? Bot 30 Star 10 Fork Olduğunda Paylaşılacaktır! Paylaşımdan Anında Haber Almak İçin Takip Edebilirsin 30 Star 10 Fork Olduğu

Oct 27, 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 !

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)

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

Sep 17, 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.

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

Dec 2, 2022

Crypto dashboard built using ReactJs , ExpressJs and RapidAPI

Crypto-Board Crypto Dashboard application built using ReactJs and NodeJs with RapidAPI Tech Stack and Dependencies Name Description ReactJs Front End

Jan 8, 2022

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
Owner
null
The authentication-server is a node app that handles user registration, authentication & authorization with JWT.

Authentication Server The authentication-server is a node app that handles user registration, authentication & authorization with JWT. Here is the REP

Oğuz Çolak 18 Jul 24, 2022
Building an API on nodejs with registration system, authentication, CRUD of projects and tasks.

api-token-express Building an API on nodejs with registration system, authentication, CRUD of projects and tasks. API endpoints POST { "username":

MrDiniz 4 Jan 15, 2022
Simple, unobtrusive authentication for Node.js.

Passport Passport is Express-compatible authentication middleware for Node.js. Passport's sole purpose is to authenticate requests, which it does thro

Jared Hanson 21k Jan 7, 2023
Authentication solution for Express

Lockit Lockit is an authentication solution for Express. Check out the demo. It consists of multiple single purpose modules: lockit-login lockit-signu

Mirco Zeiss 445 Dec 28, 2022
A small project with 3 accounts mapped to 3 resources using auth0 as an authentication service.

Auth0WithExpressJS Quickstart install dependencies for backend and start backend cd Auth0WithExpressJS\Back && npm start install dependencies for fron

RYMND 16 Aug 21, 2021
An easy to use authentication system that can easily be built in to your Express + HBS web apps.

yoAuth An easy to use authentication system that can easily be built in to your Express + HBS web apps. Currently only supports local authentication,

null 2 Jan 21, 2022
Edge-side GitHub authentication

cloudflare-workers-github-auth Edge-side GitHub authentication example. Requirements node.js (v16.13.1 or later) Installation Clone this repository an

Yoshiaki Sugimoto 7 Feb 21, 2022
Tutorial Project : NodeJs API Multi Authorization Middleware with JWT

Tutorial How to Create API with multi route prefixs as well as Multi Authorization in NodeJs Installation npm install .env modify database informatio

Aung Kyaw Nyunt 10 Dec 10, 2022
Node-sodium-jwt - Fast sodium-based crypto for signing and verifying json web tokens (JWT)

node-sodium-jwt Features Fast sodium-based crypto for hashing json web tokens (JWT) Relies on sodium-native to perform crypto. Built with TypeScript f

Olivier Louvignes 1 Jan 3, 2022
node.js auth package (password, facebook, & more) for Connect and Express apps

everyauth Authentication and authorization (password, facebook, & more) for your node.js Connect and Express apps. There is a NodeTuts screencast of e

Brian Noguchi 3.5k Dec 17, 2022