My application stores use file like the following approach:
/app
|-static
| |-img
| |-css
| |-js
|-server
| |-models
| |-routes
|-files
|- 594873
|- file.txt
.
.
|- 393948
Folder 'files' contains private user files. 594873 and 393948 are user ids. So I need to make a secure aproach for writing and reading user's files. On a backend I use NodeJS/express/mongoose.
I need to make something like this:
app.get('/getfile/:userid/:filename', function (req, res) {
// Return file that contains in 'userid' folder and named 'filename'
});
EDIT:
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')));
Say you're using something similar to Passport to authenticate users, and the user object is stored in req.user, and that object contains an id property, you can create a middleware which checks for the correct access:
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);
});