我想访问我的护照策略在其回调中指定的消息,如:done(null, false, { message: 'No such user.' });
。到目前为止,我发现可以通过将选项failureFlash: true
传递到passport.authenticate()
函数来显示这些消息,该函数的使用再次需要安装connect-flash
中间件。所以我安装了模块并将var flash = require('connect-flash);
添加到我的源代码中,并将app.use(flash());
添加到我的快速应用程序的配置方法中。但它仍然因方法.flash()
不可用的错误而崩溃。我错过了什么?
更多代码:
var http = require('http');
var express = require('express');
var passport = require('passport');
var googleStrategy = require('passport-google').Strategy;
var flash = require('connect-flash');
passport.serializeUser(function (user, done) {
done(null, user);
});
passport.deserializeUser(function (obj, done) {
done(null, obj);
});
passport.use(new googleStrategy(
{
returnURL: 'http://localhost:123456/auth/google/return',
realm: 'http://localhost:123456/'
},
function(identifier, profile, done) {
process.nextTick(function () {
User.findOne({ ID: identifier }, function (err, user) {
if (err) {
return done(err);
}
if (!user) {
return done(null, false, { message: 'no such user' });
}
return done(null, user);
});
});
})
);
var app = express();
app.configure(function() {
app.set('view engine', 'ejs');
app.set('views', __dirname + '/views');
app.use(express.logger());
app.use(express.cookieParser());
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.session({ secret: 'veryverysecretsecret' }));
app.use(passport.initialize());
app.use(passport.session());
app.use(app.router);
app.use(flash());
});
app.get(
'/auth/google',
passport.authenticate('google', { failureRedirect: '/login', failureFlash: true }),
function (req, res) {
res.redirect('/');
}
);
app.get('/auth/google/return',
passport.authenticate('google', { failureRedirect: '/login', failureFlash: true }),
function (req, res) {
res.redirect('/');
}
);
http.createServer(app).listen(123456);
答案 0 :(得分:9)
Passport需要在自身之前配置flash。
要解决您的问题,只需更改app.configure()
中的订单,然后将护照使用移到其下方,如下所示:
app.configure(function() {
app.set('view engine', 'ejs');
app.set('views', __dirname + '/views');
app.use(express.logger());
app.use(express.cookieParser());
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.session({ secret: 'veryverysecretsecret' }));
app.use(flash());
app.use(passport.initialize());
app.use(passport.session());
app.use(app.router);
});
passport.serializeUser(function (user, done) {
done(null, user);
});
passport.deserializeUser(function (obj, done) {
done(null, obj);
});
passport.use(new googleStrategy(
{
returnURL: 'http://localhost:123456/auth/google/return',
realm: 'http://localhost:123456/'
},
function(identifier, profile, done) {
process.nextTick(function () {
User.findOne({ ID: identifier }, function (err, user) {
if (err) {
return done(err);
}
if (!user) {
return done(null, false, { message: 'no such user' });
}
return done(null, user);
});
});
})
);
很高兴它有所帮助!