Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

Role based authentication in node js MongoDB

const db = require("../models");
const ROLES = db.ROLES;
const User = db.user;
checkDuplicateUsernameOrEmail = (req, res, next) => {
  // Username
  User.findOne({
    username: req.body.username
  }).exec((err, user) => {
    if (err) {
      res.status(500).send({ message: err });
      return;
    }
    if (user) {
      res.status(400).send({ message: "Failed! Username is already in use!" });
      return;
    }
    // Email
    User.findOne({
      email: req.body.email
    }).exec((err, user) => {
      if (err) {
        res.status(500).send({ message: err });
        return;
      }
      if (user) {
        res.status(400).send({ message: "Failed! Email is already in use!" });
        return;
      }
      next();
    });
  });
};
checkRolesExisted = (req, res, next) => {
  if (req.body.roles) {
    for (let i = 0; i < req.body.roles.length; i++) {
      if (!ROLES.includes(req.body.roles[i])) {
        res.status(400).send({
          message: `Failed! Role ${req.body.roles[i]} does not exist!`
        });
        return;
      }
    }
  }
  next();
};
const verifySignUp = {
  checkDuplicateUsernameOrEmail,
  checkRolesExisted
};
module.exports = verifySignUp;
Comment

PREVIOUS NEXT
Code Example
Javascript :: js hk 
Javascript :: imleç 
Javascript :: xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace 
Javascript :: add link in react table 
Javascript :: angular pipe to capitalize all letters 
Javascript :: time date utils 
Javascript :: SH1 in react native 
Javascript :: class function constructor 
Javascript :: jQuery - The noConflict() Method 
Javascript :: check if the last character of word is "A" 
Javascript :: How to Compare Strings Using Mathematical Operators 
Javascript :: weakset use cases javaScript 
Javascript :: react with two components render 
Javascript :: find parent index of nested array object javascript 
Javascript :: Create a new object where the prototype is {0:10} 
Javascript :: Using strings, the spread operator creates an array with each char in the string 
Javascript :: Backbone Save Example 
Javascript :: ticket draw 
Javascript :: pass data between componets in react 
Javascript :: toast.toastAlert ext js 
Javascript :: Naming Your Componts Vue 
Javascript :: onclick add and remove class using jquery 
Javascript :: Bootstrap 5 data attributes different from Bootstrap 4 
Javascript :: node_modules is not generated in docker 
Javascript :: check if a number is multiple of 3 javascript 
Javascript :: window handles 
Javascript :: spliting html select option 
Javascript :: with jquery Make a style menu that displays paragraphs and hides them according to the style of the slides 
Javascript :: Compare a Boolean with another value 
Javascript :: onclick switch javascript 
ADD CONTENT
Topic
Content
Source link
Name
3+6 =