【发布时间】:2014-12-11 18:54:18
【问题描述】:
我正在使用 passport.js,如果我的表单字段为空,我想闪现一条消息。但我不知道该怎么做,因为如果护照丢失,护照不会触发策略回调。我真的希望这个用例更清楚,我不想修改护照。我觉得有办法做到这一点,但我不知道在哪里!我尝试使用路由的回调 (app.post),但它似乎不像我尝试的那样工作。
这里是验证函数原型:
Strategy.prototype.authenticate = function(req, options) {
options = options || {};
var username = lookup(req.body, this._usernameField) || lookup(req.query, this._usernameField);
var password = lookup(req.body, this._passwordField) || lookup(req.query, this._passwordField);
// here is my problem
if (!username || !password) {
return this.fail({ message: options.badRequestMessage || 'Missing credentials' }, 400);
}
var self = this;
function verified(err, user, info) {
if (err) { return self.error(err); }
if (!user) { return self.fail(info); }
self.success(user, info);
}
try {
if (self._passReqToCallback) {
this._verify(req, username, password, verified);
} else {
this._verify(username, password, verified);
}
} catch (ex) {
return self.error(ex);
}
};
这是我的策略:
passport.use('local-login', new LocalStrategy({
usernameField : 'email',
passwordField : 'password',
passReqToCallback : true
},
function(req, email, password, done) {
// ...
console.log("Hello");
User.findOne({ 'local.email' : email }, function(err, user) {
if (err)
return done(err);
// if no user is found, return the message
if (!user)
return done(null, false, req.flash('loginMessage', 'Pas d\'utilisateur avec ce login.')); // req.flash is the way to set flashdata using connect-flash
// if the user is found but the password is wrong
if (!user.validPassword(password))
return done(null, false, req.flash('loginMessage', 'Oops! Mauvais password.')); // create the loginMessage and save it to session as flashdata
// all is well, return successful user
return done(null, user);
});
}));
最后是我的路线:
app.get('/login', function(req, res) {
// render the page and pass in any flash data if it exists
res.render('login', { title: "Connexion", message: req.flash('loginMessage') });
});
// process the login form
app.post('/login', passport.authenticate('local-login', {
successRedirect : '/profile', // redirect to the secure profile section
failureRedirect : '/login', // redirect back to the signup page if there is an error
failureFlash : true // allow flash messages
}, function(err, user, info) {
// Was trying this callback, does'nt work, post callback maybe ?
console.log("Hello");
}));
【问题讨论】:
-
你的玉石或模板在哪里?你应该检查
message,如果它存在则显示 -
Precision :问题是当用户或密码错误时已经有一个闪烁消息,但当字段为空时没有。而且我无法做到这一点,因为策略中的回调在这种情况下不被护照调用(请参阅身份验证原型)。我不想破解护照密码,一定有办法..
-
return this.fail({ message: options.badRequestMessage || 'Missing credentials' }, 400);
标签: javascript node.js passport.js