passport js middleware will always redirect me to the faliure route

14 Views Asked by At

please help me find the issue with my passport.js setup i swear i will never use passport again just please help me this time passport.js

const passport = require('passport');
const mongoose = require('mongoose');
const crypto = require('crypto');   
const LocalStrategy = require('passport-local').Strategy;
const User = require('../models/userModel');
const validPassword = require('../lib/passwordUtils').validPassword;

 mongoose.createConnection(//database name so i've hid it);

module.exports = function(passport) {
passport.use(new LocalStrategy(
     async function(username, password, done) {
        console.log('hi from local strategy')
        try {
            console.log('hi from local strategy')
            const user = await User.findOne({ username: username });
            if (!user) { 
                console.log('hi from local strategy - user not found') 
                return done(null, false, { message: 'Incorrect username.' });

            }

            // Hash the provided password using the user's salt and compare with stored hashed password
            const isValid =   validPassword(password, user.hash, user.salt);
            if (isValid) {
                console.log('hi from local strategy - user found and valid')
                return done(null, user);
            } else {
                console.log('hi from local strategy - user found and not valid')
                return done(null, false, { message: 'Incorrect password.' });

            }
        } catch (error) {
            console.console.error('hi forom local strategy error');
            return done(error);
        }
    }
));

passport.serializeUser(function(user, done) {
    done(null, user.id);
});

passport.deserializeUser(function(id, done) {
    User.findById(id, function(err, user) {
        done(err, user);
    });
});
};

As you can see I have put many console log statements but none of them showing me any output. I feel as if this whole middleware is not getting called or running

my app.js

const express =  require ('express')
const app = express()
const passport  = require('passport')
const mongoose = require('mongoose')
const session   = require('express-session')
const connectEnsureLogin = require('connect-ensure-login');
const {ensureAuthenticated} = require('./config/auth');
const passwordUtils = require('./lib/passwordUtils');


const { ensureAdminAuth } = require('./config/adminauth');

  mongoose.connect("//db name")

  const Users = require('./models/userModel')
  app.set("view engine", "ejs");
  app.use(express.static('public'))
   app.use(express.urlencoded({extended: false}));
   const flash = require('connect-flash');
  app.use(flash());

 app.use((req, res, next) => {
 res.locals.flashmessage = req.flash(); // Make messages available in templates
   next();
    });
 //passport confugration

  require('./config/passport')(passport);file is in './config/passport.js'
    passport.use(Users.createStrategy());
  app.use(passport.initialize());
  app.use(passport.session());



 // To use with sessions
 passport.serializeUser(Users.serializeUser());
 passport.deserializeUser(Users.deserializeUser());

the login route always redirects me to faliure and I get the faliure Flash message

enter code here
// login route 
 app.post('/login', passport.authenticate('local', {
successRedirect: '/',
failureRedirect: '/login',
failureFlash: true
    }));

my passportUtils.js

const crypto = require('crypto');

function validPassword(password, hash, salt) {
var hashVerify = 
 crypto.pbkdf2Sync(password, salt, 20000, 64,'sha512').toString('hex');                                   
 console.log('hi from password utils validpassword  hashverify--'+hashVerify)
return hash === hashVerify;
  };


function genPassword(password){
var salt = crypto.randomBytes(32).toString('hex');
var hash = crypto.pbkdf2Sync(password, salt, 20000, 64, 'sha512').toString('hex');
console.log('hi from password utils g  hash--'+hash)

return {
    salt : salt,
    hash : hash
  }

 }

 module.exports.validPassword = validPassword;
 module.exports.genPassword = genPassword;

I think I am correctly implementing the logic but login doesn't work

0

There are 0 best solutions below