0

I'm currently working on a MEAN full stack web project for a little marketplace app. This project's build in 3 parts : - server -> node.js express mongoose - front web -> angular 4 - front mobile -> ionic

I've to build this simple API REST, with a classic CRUD, but I have to use JWT to secure my adverts (for the market place). An user will be able to delete or modify only the advertisements which he himself create, using JWT verification.

Currently, I have a token verification's middle-ware, but it does not prevent a user from deleting an ad created by another user.

I'm calling my middle-ware as I understood on tutorials, it can be change.

And after a lot of research, i only found information about authentication with JWT, then if someone can help my, thanks.

//my token verification's middle-ware
function verifyToken(req, res, next) {
  var token = req.headers['x-access-token'];
  if (!token)
    return res.status(403).send({ auth: false, message: 'No token provided.' });
  jwt.verify(token, config.secret, function(err, decoded) {
    if (err)
    return res.status(500).send({ auth: false, message: 'Failed to authenticate token.' });
    // if everything good, save to request for use in other routes
    req.userId = decoded.id;
    next();
  });
}


//an example of middle-ware call
  router.delete('/:id',VerifyToken, (req, res) => {
    advertModel.findById(req.params.id, (err, advert) => {
      if(!advert){
        res.json({message:"No advert corresponding"})
      }
        advert.remove((err) => {
          if(err){
            console.log(err);
          }
             res.json({message: 'Successfully deleted'});
        });
    });
  });

This application is still under construction, then if you have any comments that would allow me to improve the few pieces of code that you see, go.

2 Answers2

0

jwt token when comes with a request, if that token is valid it just pass the request to next with that user credential, but if the token is not valid, it stops the request lifecycle. But it does not have anything to do with the things you are trying to do. You can write a simple conditional in your controller code like this

if(req.user.id !== youradd.user_id){
    return ('with valid message and http code')
shahin mahmud
  • 945
  • 4
  • 11
0

@shahinmahmud is right. Basically there are two parts to what you are doing. Authentication and Authorization. Authentication is done by JWT token validation. Authorisation is to restrict access based on the user. In your case, if it's just access to one resource, a simple if-else will do. Otherwise you need to look into some user management libraries.

This definition should probably help

yaswanth
  • 2,349
  • 1
  • 23
  • 33
  • Okay, thank's to your help i understand better, i have to use jwt to recover userId from token, and use this userId for Authorization. – Julien Galland Jun 26 '18 at 09:19