Advertisement
Guest User

Untitled

a guest
Nov 16th, 2018
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. export function requireRoles(allowedRoles) {
  2.   return (req, res, next) => {
  3.     // Check if user is authenticated
  4.     const userRoles = req.user.Roles;
  5.     let hasRole = false;
  6.  
  7.     // in the case we are not authenticated
  8.     if (!req.user) {
  9.       console.log("not authed\n");
  10.       return res.sendStatus(403);
  11.     }
  12.  
  13.     // in the case we have no roles
  14.     if (allowedRoles.length <= 0) {
  15.       console.log("There are no roles to match\n");
  16.       return next();
  17.     }
  18.  
  19.     // check to see if any of my roles exist in the allowed roles
  20.     if (userRoles.length > 0) {
  21.       _.each(userRoles, (userRole) => {
  22.         _.each(allowedRoles, (allowedRole) => {
  23.           // console.log('iterating');
  24.           if ((allowedRole === userRole.name) && !hasRole) {
  25.             console.log("My role matches\n");
  26.             hasRole = true;
  27.             return next();
  28.           }
  29.         });
  30.       });
  31.       if (!hasRole) {
  32.         console.log("None of my roles match\n");
  33.         return res.sendStatus(403);
  34.       }
  35.     }
  36.     else {
  37.       console.log("I have no roles\n");
  38.       return res.sendStatus(403);
  39.     }
  40.   };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement