Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

165
Visualizações
Node Js pass the role as a string to the JWT verification function

the JWT verification function accepts the req, res and next as its params. I need to pass an additional string 'Admin' so that only admin users may access this API

My jwtVerification.js code:

module.exports = async function (req, res, next) { //I need to be able to add role to this call
    try {       
        const token = req.header("Authorization");

        if (!token) return res.status(401).send('Invalid access token.');

        const _token = token.substring(7, token.length);

        const decoded = jwt.verify(_token, process.env.JWT_PRIVATE_KEY)

        const user = await prisma.user.findFirst({ where: { id: decoded.id } });

        if (!user) return res.status(401).send('Invalid access token.');
     
        //I need to be able to read the role so that I can do the following verifications
        //if(!role) next();
        //else{
        //   if(user.role !== role || decode.role !== role) return res.status(403).send('Forbidden!')
        //   else next();
        //}
        next();

    } catch (error) {
        res.status(401).send(error.message);
    }
};

finally, the API call itself: //use verifyJWT('Admin') for example

router.post('/test', verifyJWT, async (req, res) => {
    res.send('hi');
})
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You cat use some thing like this:

module.exports = function (myParam) => {
    
         return async function (req, res, next) { 
            //use myParam here
            try {       
                const token = req.header("Authorization");

                if (!token) return res.status(401).send('Invalid access token.');

                const _token = token.substring(7, token.length);

                const decoded = jwt.verify(_token, process.env.JWT_PRIVATE_KEY)

                const user = await prisma.user.findFirst({ where: { id: decoded.id } });

                if (!user) return res.status(401).send('Invalid access token.');
             
                //I need to be able to read the role so that I can do the following verifications
                //if(!role) next();
                //else{
                //   if(user.role !== role || decode.role !== role) return res.status(403).send('Forbidden!')
                //}
                next();

            } catch (error) {
                res.status(401).send(error.message);
            }
    }
};

And after that use the middleware this way:

router.post('/test', verifyJWT(someParam), async (req, res) => {
    res.send('hi');
})
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda