在Express中提供目录之前进行身份验证

时间:2014-10-09 17:43:20

标签: javascript node.js authentication express routes

在查看快速目录文件树之前,我无法尝试对用户进行身份验证。我可以在所有其他页面上进行身份验证,但不能在" / dat /:file(*)"即使我在下载文件之前通过了身份验证路由。   因此,当用户转到' /'时,如果用户没有登录,快递会重定向他们。但是,如果用户转到' / dat',快递将不会进行身份验证,并且会允许他们浏览文件树。我使用express@3.4.8,任何帮助都会很棒。谢谢!

app.configure( function() {
    app.set('views', __dirname + '/views');
    app.set('view engine', 'jade');

    app.use('/', express.static(__dirname + '/public'));
    app.use('/dat', express.directory(__dirname + '/public/dat', {hidden: true, icons: true}));

    app.use(express.json());
    app.use(express.urlencoded());
    app.use(express.methodOverride());
    app.use(express.cookieParser('secret'));
    app.use(express.session({
        secret: 'secret',
        maxAge: 3600000
    }));
    app.use(passport.initialize());
    app.use(passport.session());
    app.use(app.router);
});

app.get('/', ensure_authenticated, routes.index);
app.get('/dat/:file(*)', ensure_authenticated, function(req, res, next) {
    var path = __dirname + '/' + req.params.file;
    res.download(path);
});

1 个答案:

答案 0 :(得分:1)

中间件的顺序很重要。

app.use('/dat', express.directory(__dirname + '/public/dat', {hidden: true, icons: true}));

之前:

app.get('/dat/:file(*)', ensure_authenticated, function(req, res, next) {
    var path = __dirname + '/' + req.params.file;
    res.download(path);
});

因此,第一个中间件正在处理请求。

app.use(app.router))之后移动第一条路线应解决此问题。

如果您希望对用户进行身份验证以查看目录列表,您还希望将ensure_authenticate添加到express.directory的路由中。

app.use('/dat', ensure_authenticate, express.directory ...
相关问题