ankakusu
ankakusu

Reputation: 1828

Passport.js LocalStrategy logic

I want to understand how does LocalStrategy work.

Here is a part of my server file:

var passport = require('passport');
var express = require('express');
/* other initializations */
var app = express();

passport.use = new LocalStrategy(
        function(email, password, done) {
            module.exports.findByUsername(email, function(err, user){
                if (err) throw err;
                if(!user) {
                    done(null, false, { message: 'Incorrect username.' });
                }
                else if(user.password != password) {
                    done(null, false, { message: 'Incorrect password.' });
                }
                else {
                    return done(null, user);
                } 
            });
        }
    )

app.post("/login" 
    , passport.authenticate('local',{
        successRedirect : "/",
        failureRedirect : "/login",
    }) ,
    function(){
        console.log("post /login");
    }
);

Now, from a client browser, I'm sending a http post request to http://localhost:8000/login . If authentication is success then user will be redirected to the root page "/" and if failure, user will be redirected to login page again.

The question is, when we are defining a new LocalStrategy, I define a function(email,password, done){...}. However, when I'm calling this function at app.post("/login", ...){...} how do I pass the email and password parameters?

Upvotes: 1

Views: 1251

Answers (1)

Plato
Plato

Reputation: 11052

passport assumes by default that you POST a form with input name='username' input name='password'. override it as described in passport docs:

passport.use(new LocalStrategy({
    usernameField: 'email',
    passwordField: 'password'
  },
  function(email, password, done) {
    // ...
  }
));

Upvotes: 1

Related Questions