2014-11-14 26 views
0

如果我有一个用户使用id = 555,一个Web应用程序我怎么只给他下访问网址:Node.js的使用Express - 无法访问某些网址

www.example.com/users/555/home 

,并阻止他进入

www.example.com/users/554/home 

etc?

这样做的最好方法是什么?我目前使用Passport.js进行身份验证。

回答

2

在Express 4中,use()可以采用路径。所以,非常松散(可能有错误),您的应用程序前把这个,get()方法,app.put()等等......

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! 
}); 

不像JimmyRare答案,这涵盖了所有的HTTP动词和所有用户。

加入:我对passport.js不熟悉,所以需要由其他人填写。护照专家,请随时编辑这个答案。

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

你需要重复PUT,POST等... – user949300