【发布时间】:2017-01-05 12:20:12
【问题描述】:
到目前为止我有这个代码
app.post('/login', passport.authenticate('local', {
failureRedirect: '/login',
failureFlash: true
}), function(req, res) {
return res.redirect('/profile/' + req.user.username);
});
成功登录正在工作。但是,当登录失败时,它会通过GET 请求重定向到/login。所以我需要一些额外的代码来处理这种情况:
app.get('/login', ...);
我需要以这样一种方式实现它,如果POST 失败并重定向到这个GET,它将发送使其失败的用户名。这样我就可以将用户名重新填充到表单中,这样每次有人由于用户名错误而尝试登录失败时,它就不会被清除。
我怎样才能做到这一点?
编辑:这就是我编写策略的方式。
passport.use(User.createStrategy());
用户.js
var mongoose = require('mongoose'),
Schema = mongoose.Schema,
passportLocalMongoose = require('passport-local-mongoose');
var User = new Schema({
username: String,
firstName: String,
lastName: String,
dateOfBirth: Date,
email: String,
mobileNumber: Number,
favouriteWebsite: String,
favouriteColour: String
});
User.methods.getFullName = function() {
return this.firstName + " " + this.lastName;
}
User.methods.getAge = function() {
return ~~((Date.now() - new Date(this.dateOfBirth)) / (31557600000));
}
User.plugin(passportLocalMongoose, {
usernameQueryFields: ["username", "email"], // TODO not working
errorMessages: {
IncorrectPasswordError: "Incorrect password!",
IncorrectUsernameError: "Username does not exist!"
}
});
module.exports = mongoose.model("User", User);
【问题讨论】:
标签: javascript express passport.js