I currently have this block of code:
app.post('/login', passport.authenticate('local', {
failureRedirect: '/login',
failureFlash: true
}), function(req, res) {
return res.redirect('/profile/' + req.user.username);
});
The successful login functionality is working as expected. However, in cases where the login fails, the redirection is done via a GET
request to /login
. To handle this scenario, additional code like below needs to be implemented:
app.get('/login', ...);
In order to populate the username back into the form when there is a failed POST
redirecting to the GET
, I need to send the username that caused the failure. This way, the username field doesn't get cleared every time someone unsuccessfully tries to log in due to an incorrect username.
Is there a way to achieve this?
UPDATE: Here is how I set up my strategy.
passport.use(User.createStrategy());
User.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);