我的应用程序商店使用类似以下方法的文件:
/app
|-static
| |-img
| |-css
| |-js
|-server
| |-models
| |-routes
|-files
|- 594873
|- file.txt
.
.
|- 393948
文件夹'文件'包含私人用户文件。 594873和393948是用户ID。所以我需要为编写和阅读用户文件做出安全的准备。在后端我使用NodeJS / express / mongoose。
我需要做这样的事情:
app.get('/getfile/:userid/:filename', function (req, res) {
// Return file that contains in 'userid' folder and named 'filename'
});
编辑:
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser());
app.use(express.session());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'static')));
答案 0 :(得分:0)
假设您正在使用类似于Passport的内容来验证用户,并且用户对象存储在req.user
中,并且该对象包含id
属性,您可以创建中间件检查正确的访问权限:
var checkValidUser = function(req, res, next) {
if (req.user && req.user.id && req.user.id === req.params.userid)
{
// user has access, calling 'next()' will pass the request to the handler
next();
}
else
{
// user doesn't have access, return an HTTP 401 response
res.send(401, 'Unauthorized');
}
};
app.get('/getfile/:userid/:filename', checkValidUser, function (req, res) {
// this will only be called when 'checkValidUser' allowed access to this file
res.sendfile('./files/' + req.params.userid + '/' + req.params.filename);
});