简体   繁体   中英

Node.js with Express - preventing access to certain URLs

If I have a user to a web application with id=555, how do I give him access to URLs only under:

www.example.com/users/555/home

and prevent him from getting to

www.example.com/users/554/home

etc?

what is the best way to do that? I am currently using Passport.js for authentication.

In Express 4, use() can take a path. So, very loosely ( and likely with errors) put this before your app,get(), app.put() etc...

app.use('/users/:id/:dir', function(req, res, next){
  if (checkAuth(lots of args)). // you have an id, dir, etc...
     next();  // user is o.k. to proceed
  else
     send a 400 or whatever;  and don't call next!
});

Unlike the JimmyRare answer, this covers all the HTTP verbs and all users.

Added : I'm not familiar with passport.js so that part needs to be filled in by somebody else. Passport experts, please feel free to edit this answer.

app.get('/users/:id/home', function(req, res) {
  if(req.params.id == 554) {
    res.send('Thy art not allowed!');
  }
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM