Ogen
Ogen

Reputation: 6709

Passport.js custom callback passing parameter

I have this code so far

app.post('/login', passport.authenticate('local', {
        failureRedirect: '/login',
        failureFlash: true
    }), function(req, res) {
        return res.redirect('/profile/' + req.user.username);
    });

A successful login is working. However, when the login fails, it gets redirected via GET request to /login. So I'd need some additional code like this to handle that situation:

app.get('/login', ...);

I need to implement this in such a way that if the POST fails and redirects to this GET it will send the username that made it fail. This is so I can populate the username back into the form so it doesn't get cleared everytime someone tries to log in unsuccessfully due to an incorrect username.

How can I achieve this?

EDIT: This is how I wrote 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);

Upvotes: 1

Views: 1842

Answers (1)

Aᴍɪʀ
Aᴍɪʀ

Reputation: 7803

You can call passport.authenticate yourself with (req, res, next). It accepts a callback function as its input so you can determine if the process was successful or not.

app.post('/login', function(req, res, next) {
  passport.authenticate('local', function(err, user, info) {
    if (err || !user) {
      // failed
    } else {
      // successful
    }
  })(req, res, next);
});

You might want to handle err and !user (user === false) separately. err means there was some internal errors in the process, but user would be false when the user doesn't exist. It depends how you wrote the strategy though.

Upvotes: 3

Related Questions