我基本上在寻找同样的东西。具体来说,我想要以下内容:
- 使用 express.js,它封装了 Connect 的中间件功能
- “基于表单”的身份验证
- 对哪些路由进行身份验证进行精细控制
- 用户/密码的数据库后端
- 使用会话
我最终做的是创建自己的中间件函数check_auth,我将其作为参数传递给我想要验证的每个路由。 check_auth 仅检查会话,如果用户未登录,则将其重定向到登录页面,如下所示:
function check_auth(req, res, next) {
// if the user isn't logged in, redirect them to a login page
if(!req.session.login) {
res.redirect("/login");
return; // the buck stops here... we do not call next(), because
// we don't want to proceed; instead we want to show a login page
}
// the user is logged in, so call next()
next();
}
然后对于每个路由,我确保这个函数作为中间件传递。例如:
app.get('/tasks', check_auth, function(req, res) {
// snip
});
最后,我们需要实际处理登录过程。这很简单:
app.get('/login', function(req, res) {
res.render("login", {layout:false});
});
app.post('/login', function(req, res) {
// here, I'm using mongoose.js to search for the user in mongodb
var user_query = UserModel.findOne({email:req.body.email}, function(err, user){
if(err) {
res.render("login", {layout:false, locals:{ error:err } });
return;
}
if(!user || user.password != req.body.password) {
res.render("login",
{layout:false,
locals:{ error:"Invalid login!", email:req.body.email }
}
);
} else {
// successful login; store the session info
req.session.login = req.body.email;
res.redirect("/");
}
});
});
无论如何,这种方法主要是为了灵活和简单而设计的。我相信有很多方法可以改进它。如果您有任何意见,我非常希望收到您的反馈。
编辑:这是一个简化的例子。在生产系统中,您永远不想以纯文本形式存储和比较密码。正如评论者指出的那样,有一些库可以帮助管理密码安全。