User authentication and authorization Middleware

Last modified: May 04, 2022
  • verifyToken checks if token is valid
  • isUser checks if a user has 'user' role
  • isAdmin checks if a user has 'admin' role
const jwt = require("jsonwebtoken"); require('dotenv').config(); const db = require("../db/models/index"); const User = db.user; const UserRole = db.userrole; verifyToken = (req, res, next) => { let token = req.headers["x-access-token"]; if (!token) { return res.status(403).send({ message: "No token provided!" }); } jwt.verify(token, process.env.JWT_SECRET_KEY, (err, decoded) => { if (err) { return res.status(401).send({ message: "Unauthorized!" }); } req.userId = decoded.id; next(); }); }; isUser = (req, res, next) => { User.findByPk(req.userId).then(user => { //get user information const role = UserRole.findAll({ //get user role and check if user has user role where:{ userId: user.id, roleId: process.env.UserRoleId } }).then(ur =>{ if(ur.length > 0){ next(); return; } else{ res.status(403).send({ message: "Require Admin Role!" }); } }); }); }; isAdmin = (req, res, next) => { User.findByPk(req.userId).then(user => { //get user information const role = UserRole.findAll({ //get user role and check if user has admin role where:{ userId: user.id, roleId: process.env.AdminRoleId } }).then(ur =>{ if(ur.length > 0){ next(); return; } else{ res.status(403).send({ message: "Require Admin Role!" }); } }); }); }; const authJwt = { verifyToken: verifyToken, isUser: isUser, isAdmin: isAdmin }; module.exports = authJwt;