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

91
Visualizações
How to find a Forum or a Node by passing a JWT Token?

I would like to know how I can find my forum using my JWT token

exports.getByOwnerID = function (req, res, next) {
  Forum.find({createdBy: req.body.createdBy})
  .then(doc => {
      if(!doc) { return res.status(400).end();}
      return res.status(200).json(doc);
  })
  .catch(err => next(err));
}

So here I have my function to verify my JWT Token I use it for example this way

this is my route : router.post('/',verifyToken,getOwner);

this is my request : POST http://localhost:8080/forum/getOwner Authorization: Bearer {token}

const extractToken = (rawTokenHeader) => {
  
  if(!rawTokenHeader) { return undefined; }

  // Remove bearer and extract token value
  const temp = rawTokenHeader.split(' ');
  if(!temp || temp.length != 2) { return undefined; }

  // Return encoded token
  return temp[1];

};

module.exports = function(req,res,next){
  // Get authorization header
  const rawTokenHeader = req.header('Authorization');

  // Get token value
  const token = extractToken(rawTokenHeader);

  // No token -> No access
  if(!token) {
    console.log('No token in request');
    // Access denied
    return res.status(401).send('Access Denied');
  }
  
  // Verify token
  try {
    const decoded = jwt.verify(token, process.env.JWT_KEY);

    req.token= decoded;
    req.user = decoded;
    //console.log(token.userID);
        // Proceed
    next();
  } catch(err) {
    console.error('Error in JWT check: ', err);
    // Tell client something went wrong
    res.status(400).send('Invalid Token');
  }
}
const forumSchema = ({
    forumName: {
        type: String,
        required: true,
    },
    forumDescription: {
        type: String,
        required: true,
    },
    createdBy: { 
        type: Schema.Types.ObjectId, ref: 'User' 
    },
    published_on: {
        type: String,
        default: moment().format("LLL")
    },
});

I´ve tried a lot of things but I can´t solve it anymore.. I need help

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

How I don't have enough reputation to make a comment I leave this as an answer, is hard to say why this is not working if we don't know how the schema of Forum looks like and what is returning req.body.createdBy, but if the jwt is created by you could encode the Forum._id in it and when you receive it here you can decode it and find the forum in the database

edit---

Now that I can see the error you got and the Schema of Forum i can say that probably you can solve the error by importing mongoose and adding this at the query mongoose.Types.ObjectId(req.body.CreatedBy) that will parse the string to an objectId

about 4 years ago · Juan Pablo Isaza Relatório

0

As you can see, you have user (or token) data in the req object, and I hope your jwt token also includes the user's id. You can use the user id to find their Forums.

According to the router router.post('/', verifyToken, getOwner); (getByOwnerID ???), let's update getOwner handler:

exports.getOwner = function (req, res, next) {
  Forum.find({ createdBy: req.user.userID }) // or something like that
  .then(doc => {
      if(!doc) { return res.status(400).end();}
      return res.status(200).json(doc);
  })
  .catch(err => next(err));
}
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