Thursday, 27 April 2017

How to change passport to use email instead of username for authenticating?

I wanna use user's email and password for logging in. But in passport you should use username.

I've tried many examples about how to do that. But non worked. The real problem is when application wants to save the record into database. Although I have change the code to look for email not username field, this is the final record saved to database:

'name': 'joseph',
'username' : 'example@gmail.com',
.
.

But I don't want the email to be save as username. And when I change it with mongoose after user registration it would be correct but again the problem will come when app wants to authenticate user.

It will look for username field in database not email. Because user will provide email as the username, login will fail.

Code:

app.get("/register", function(req, res) {
   var newUser = new User({
    username :  req.body.username,
    email :  req.body.email,
    name: req.body.name
  });

  User.register(newUser, req.body.password, function(err, user) {
    if (err) {
      req.flash('error', "An error ocurred, please try again.");
      return res.redirect('back');
    } else {
      passport.authenticate("local")(req, res, function() {
        req.flash("success", "Welcome");
        res.redirect("/admin");
      });
    }
  });

});

This code register user the way I want, but the problem is about login:

router.post('/login', middleware.outLoggedIn, passport.authenticate("local", {
    successRedirect: "/admin",
    failureRedirect: "/login",
    failureFlash: "Invalid username or password",
    successFlash: "Welcome!"
}));

It always fails, because it will get user email provided in login form, then it'll compare it with the one in database. And since I have saved the user with email and username, it will compare the provided email in login form with username field in database. AND FAIL.

This is the user in databse:

{
    "_id" : ObjectId("5901cc5c0256ed17b4d61960"),
    "salt" : "---",
    "hash" : "---",
    "username" : "joseph320",
    "email" : "example@gmail.com",
    "name" : "joseph",
    "__v" : 0
}

(Login form requires email and password)

I have also done this:

passport.use(new localStrategy({
  usernameField: 'email'
}, User.authenticate()));

I really appreciate it if you can show me how to fix that.



via Joseph

No comments:

Post a Comment