Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- export function requireRoles(allowedRoles) {
- return (req, res, next) => {
- // Check if user is authenticated
- const userRoles = req.user.Roles;
- let hasRole = false;
- // in the case we are not authenticated
- if (!req.user) {
- console.log("not authed\n");
- return res.sendStatus(403);
- }
- // in the case we have no roles
- if (allowedRoles.length <= 0) {
- console.log("There are no roles to match\n");
- return next();
- }
- // check to see if any of my roles exist in the allowed roles
- if (userRoles.length > 0) {
- _.each(userRoles, (userRole) => {
- _.each(allowedRoles, (allowedRole) => {
- // console.log('iterating');
- if ((allowedRole === userRole.name) && !hasRole) {
- console.log("My role matches\n");
- hasRole = true;
- return next();
- }
- });
- });
- if (!hasRole) {
- console.log("None of my roles match\n");
- return res.sendStatus(403);
- }
- }
- else {
- console.log("I have no roles\n");
- return res.sendStatus(403);
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement