The "local" function in passport.authenticate is not being invoked for some reason

26 views Asked by At
const express = require('express');
const jwt = require('jsonwebtoken');
const passport = require('passport');
const localStrategy = require('passport-local').Strategy;

const router = express.Router();

passport.use(
    new localStrategy(async (email , password , done)=>{
        try{
            const user = {email: "piyu" , password: "123"} 
            return done(null , user)
        }
        catch(err){
            return done(err)
        }
    })
)


...


router
    .route('/login')
    .get(async (req , res) => {
        return res.render("login")
    })
    .post( async (req , res , next) => {
        passport.authenticate('local' , async (err , user , info )=>{
            if(err){
                return next(err.message);
            }
            if(!user){
                return res.send("user not found")
            }
            if(user){
                return res.send("user found successfully")
            }
            
        })(req , res , next)
    })

module.exports = router;

Here I have hardcoded some stuff because I was trying things out. Inside "passport.use" i have hardcoded user object, so that the callback function in "passport.authenticate" should always receive user object and print "user found successfully". But for some reason the opposite has been happening and "user not found" has been printing on the webpage.

I tried console.log(user) inside the "passport.authenticate" and found that the callback function has not received user object or error . So i tried console.log("123") inside passport.use and found that when "local" function is called from "passport.authenticate" the "passport.use" is never being called or invoked for some reason.

EDIT: okay I've found that the problem was in synatx as is replaced

passport.use(new localStrategy(
  async (email, password, done) => {
    try {
        const user = { email: "piyu", password: "123" };
        return done(null, user);
    } catch (err) {
        return done(err);
    }
}));

with

passport.use(new localStrategy({
    usernameField: 'email',
    passwordField: 'password'
  },
  async (email, password, done) => {
    try {
        const user = { email: "piyu", password: "123" };
        return done(null, user);
    } catch (err) {
        return done(err);
    }
}));
0

There are 0 answers