简体   繁体   English

如果当前用户的 id 与所述路由中的 id 匹配,如何仅允许访问该路由? 节点

[英]How to only allow access to a route if the current user's id matches the id in said route? NodeJS

I have a route similar to this:我有一条与此类似的路线:

router.get("/users/:id/thing", middlewareObj.isLoggedIn, function(req, res){
    res.render("thing.ejs");
});

I want this route to only be accessible if the current user's id matches the ":id" in the route.我希望只有当前用户的 id 与路由中的“:id”匹配时才能访问此路由。 How would I go about doing this?我该怎么做呢? Much appreciated.非常感激。

You can compare the logged user (I am assuming you have it in req.user [indeed you should check on passport]) with the param ID:您可以将登录的用户(我假设您在 req.user [确实应该检查护照] 中有它)与参数 ID 进行比较:

if(req.user.id != req.params.id) return res.status(400);

You could remove the id from the URL and simply use the logged user data.您可以从 URL 中删除 id 并简单地使用记录的用户数据。 Because if the url id matches the user id, you have something redundant.因为如果 url id 与用户 id 匹配,则您有一些多余的东西。 So, with this..所以,有了这个..

router.get("/users/thing", middlewareObj.isLoggedIn, function(req, res){
  let id = req.user.id;

  //do something with the ID which you assume you do, otherwise why you want the ID in the first place

  ...

  //return the view  
  res.render("thing.ejs");
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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