Jair Bolsonaro
Jair Bolsonaro

Reputation: 11

Pass Parameter to Function Express JS

everything good ? I would like to know the best way and if it is possible to send a certain parameter to an express function in the NodeJS.

i wanna pass the string ('admin') or other string that i want to function 'RoleTolen', using my route.

function verifyToken

function verifyToken(req, res, next) {
  // Get auth header value
  const bearerHeader = req.headers["authorization"];
  // Check if bearer is undefined
  if (typeof bearerHeader !== "undefined") {
    // Split at the space
    const bearer = bearerHeader.split(" ");
    // Get token from array
    const bearerToken = bearer[1];
    // Set the token
    req.token = bearerToken;
    // Next middleware
    next();
  } else {
    // Forbidden
    res.sendStatus(403);
  }
}

function ValidToken

function validToken(req, res, next) {
  jwt.verify(req.token, process.env.SECRET, (err, authData) => {
    if (err) {
      res.sendStatus(403);
    } else {
      next();
    }
  });
}

function RolesToken

function rolesToken(role, req, res, next) {
  var decoded = jwt.decode(req.token);
  if (!decoded.permissions.includes(role)) {
    res.json("sem permissao");
  } else {
    next();
  }
}

my route

router.post(
  "/posts",
  verifyToken,
  validToken,
  rolesToken("admin"),
  customerController.posts
);

Upvotes: 0

Views: 2316

Answers (2)

laxman
laxman

Reputation: 2100

from the docs Define error-handling middleware functions in the same way as other middleware functions, except with four arguments instead of three, specifically with the signature (err, req, res, next)):

Therefore your RolesTaken function won't work as expected.

Secondly, you can create a middleware or modify existing one

(req, res, next) => {
  //some stuff

   if(req.path == '/posts') req.role= 'admin';
   if(req.path == '/someOtherPath') req.role= 'someRole';

  //some other stuff
}

Now you can get the get the role in req.someProp in the your controller middlerware as req.role

you would like to see this question also

Upvotes: 0

woozyking
woozyking

Reputation: 5220

function rolesToken(role, req, res, next) is not a proper Express.js route handler, as you already know (and hence the question, I assume).

What you can do is to write your rolesToken as a function that returns the actual Express.js compliant handler (function):

function rolesToken(role) {
  return function(req, res, next) {
    var decoded = jwt.decode(req.token);
    if (!decoded.permissions.includes(role)) {
      res.json("sem permissao");
    } else {
      next();
    }
  };
}

Upvotes: 3

Related Questions