我花了大量的时间搞清楚所有的运动部件,以获得护照带帆的工作对我blog
我会重新发布下面的相关部分,另外还有政策的变化我做了。
我创建了一个passport.js文件来管理我的护照配置/策略登记
/config/passport.js
var passport = require('passport'),
LocalStrategy = require('passport-local').Strategy;
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
User.findOneById(id).done(function (err, user) {
done(err, user);
});
});
passport.use(new LocalStrategy({
usernameField: 'email',
passwordField: 'password'
},
function(email, password, done) {
User.findOne({ email: email}).done(function(err, user) {
if (err) { return done(err); }
if (!user) { return done(null, false, { message: 'Unknown user ' + email }); }
if (user.password != password) { return done(null, false, { message: 'Invalid password' }); }
return done(null, user);
});
}
));
然后我用了一个政策,以验证身份验证。如果发出套接字请求,它将使用护照会话。
/api/policies/isAuthenticated.js
module.exports = function(req, res, next) {
// User is allowed, proceed to the next policy,
// or if this is the last policy, the controller
// Sockets
if(req.isSocket)
{
if(req.session &&
req.session.passport &&
req.session.passport.user)
{
//Use this:
// Initialize Passport
sails.config.passport.initialize()(req, res, function() {
// Use the built-in sessions
sails.config.passport.session()(req, res, function() {
// Make the user available throughout the frontend
//res.locals.user = req.user;
//the user should be deserialized by passport now;
next();
});
});
//Or this if you dont care about deserializing the user:
//req.user = req.session.passport.user;
//return next();
}
else{
res.json(401);
}
}
else if (req.isAuthenticated()) {
return next();
}
else{
// User is not allowed
// (default res.forbidden() behavior can be overridden in `config/403.js`)
return res.redirect('/account/login');
}
};
这很聪明,但解除内部Sails事件如'router:request'不是很好的做法;将它们视为私人API。如果未来核心路由器的实施发生变化,这将会中断。能够通过套接字登录/登出可能并不重要,这也是我可以考虑使用套接字进行套接字的唯一原因,但是如果您真的想要更好的地方将在策略中,或者“之前“在[自定义钩子]路线(https://github.com/balderdashy/sails-docs/blob/master/concepts/extending-sails/Hooks/customhooks.md)(确保检查req.isSocket)。 – sgress454
我知道这是不好的做法,但我真的需要护照与套接字配合使用。我发现只有这个解决方案可以帮助我。你的想法与自定义钩很好,谢谢:) – ghaiklor
看到[这里](https://github.com/kasperisager/sails-generate-auth/issues/11#issuecomment-49125634)为例在政策中做。 – sgress454