【发布时间】:2016-02-01 15:57:58
【问题描述】:
我已经看到很多示例,说明如何将身份验证中间件添加到某些需要限制为登录用户的路由(暗示默认是允许任何人访问页面),但我不知道如何使所有路由默认都需要登录,并在匿名用户应该可用的路由中选择性地选择某些路由。
有什么办法让它像这样工作吗?我正在使用 Express 4。
【问题讨论】:
标签: javascript node.js express
我已经看到很多示例,说明如何将身份验证中间件添加到某些需要限制为登录用户的路由(暗示默认是允许任何人访问页面),但我不知道如何使所有路由默认都需要登录,并在匿名用户应该可用的路由中选择性地选择某些路由。
有什么办法让它像这样工作吗?我正在使用 Express 4。
【问题讨论】:
标签: javascript node.js express
我会使用:https://github.com/expressjs/session,一旦用户通过身份验证,您就可以在控制器中检查处理 express 路由的有效会话。
更新答案
这就是我将如何登录控制用户
/**
* Module dependencies
*/
var express = require('express'),
http = require('http'),
session = require('express-session'),
app = module.exports = express();
/**
* Configuration
*/
// all environments
app.set('port', process.env.PORT || 3000);
app.set('trust proxy', 1);
app.use(session({
secret: 'keyboard cat',
resave: false,
saveUninitialized: true,
cookie: {
secure: true
}
}));
function checkUserLoggedIn(req, res, next) {
return req.session;
}
/**
* Routes to control by default is logged in with a regular expression
*/
app.get('/user/:use_id/*', function (req, res, next) {
if (checkUserLoggedIn(req)) {
console.log('User logged');
next();
} else {
console.log('error');
}
});
/**
* User Home
*/
app.get('/user/:use_id/home/', function (req, res, next) {
if (checkUserLoggedIn(req)) {
console.log('User logged goes to home');
next();
} else {
console.log('error');
}
});
/**
* Home for user that is actually logged
*/
app.get('/guest/dashboard', function (req, res, next) {
console.log('This is guest dashboard');
});
/**
* Home for user that is actually logged
*/
app.get('/guest/home', function (req, res, next) {
console.log('This is guest home');
});
/**
* Start Server
*/
http.createServer(app).listen(app.get('port'), function () {
console.log('Express server listening on port ' + app.get('port'));
});
然后运行
$ node app.js
转到浏览器并访问http://localhost:3000/home
您定义的用于控制“/*”的正则表达式正在获取所有默认路由,然后转到下一个匹配的路由,即 /home。
这是一种方法,可能有更好、更清晰的方法来解决这个问题。在正则表达式中,您可以控制默认路由的含义以及每种情况的具体含义。
【讨论】:
/* 路由模式需要从其模式中专门排除每个不受保护的路由,这似乎很乏味。