Node.js 的 Passport 中间件 [英] Passport middleware for Node.js
问题描述
我正在为 Node.js 使用 Passport 身份验证中间件.我想在我自己的对象中使用它(而不是在路由定义中内联).这样做的原因是身份验证机制会根据应用程序设置而变化,我希望保持关注点和可测试性的分离.
I am using Passport authentication middleware for Node.js. I would like to use it from within my own objects (rather than inline in a route definition). The reason for this that the auth mechanism will change depending on application settings and I would like to maintain separation of concerns and testability.
文档中的使用示例:
app.post('/session/create',
passport.authenticate('local', { failureRedirect: '/login' }),
function(req, res) {
res.redirect('/');
});
我想要这样的东西:
app.post('/session/create', sessionController.create);
...其中会话控制器通过 Passport 封装了身份验证的协调.
...where session controller encapsulates the coordination of authentication via Passport.
有人可以帮助我以这种方式组织我对 Passport 的使用吗?
Can someone help me structure my use of Passport in this way?
推荐答案
这是我正在使用的示例:
Here is an example I am using :
// Bootstrap controllers
var controllers_path = __dirname + '/controllers';
fs.readdirSync(controllers_path).forEach(function(file) {
if (~file.indexOf('.js')) {
app.controllers[file.slice(0, - 3)] = require(controllers_path + '/' + file);
}
});
我的路由器:
app.server.post('/login', app.controllers.users.doLogin);
还有我的用户控制器:
exports.doLogin = function(req, res, next) {
app.passport.authenticate('local', function(err, user, info) {
if (err) {
return next(err);
}
if (!user) {
req.flash('error', 'Invalid username or password');
return res.redirect('/login' + (req.body.target ? '?target=' + req.body.target : ''));
}
req.logIn(user, function(err) {
if (err) {
return next(err);
}
return res.redirect(req.body.target || '/');
});
})(req, res, next);
});
这篇关于Node.js 的 Passport 中间件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!