[英]Express Static for Authenticated Users
How can I enable static directories just for a user's session in express? 如何为Express中的用户会话启用静态目录? Using some HTML files as an examples, I know I can serve a directory called private via the call below 以一些HTML文件为例,我知道我可以通过下面的调用提供一个名为private的目录
app.use("/private", express.static(appDir + '/private'));
What I would like to do is just enable the static resource once a user has been authenticated (using stormpath as my example). 我想做的只是在用户通过身份验证后启用静态资源(以stormpath为例)。
For example, the function below would check if the user existed in stormpath and if they did, the app would then serve the static directory of maps. 例如,下面的函数将检查用户是否存在于Stormpath中,如果存在,则该应用程序将为地图提供静态目录。
app.get('/getPrivate', stormpath.getUser, function(req, res) {
if(req.user){
app.use("/private", express.static(appDir + '/private'));
res.redirect('/private/index.html');
}else{
//your not logged in.... redirect to login page
}
});
This does not work as I've found once I enable the static directory for a user, another user would then be able to visit the private directory without logging in. 一旦我为一个用户启用了静态目录,这将无法正常工作,然后另一个用户无需登录即可访问私有目录。
If you want to require authentication for a route, you should use stormpath.loginRequired
. 如果要对路由进行身份验证,则应使用stormpath.loginRequired
。 If the user is not logged in, they will be redirected to the login page. 如果用户未登录,他们将被重定向到登录页面。
Using app.all in my routes did the trick 在我的路线中使用app.all可以达到目的
var path = require('path');
var express = require('express');
var appDir = path.dirname(require.main.filename);
app.all('/private/*', stormpath.getUser, function(req, res, next) {
if(req.user){
next();
}else{
//you are not logged in.... redirect to login page
res.redirect('/');
}
});
app.use("/private", express.static(appDir + '/private'));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.