passport.authenticate() failing

Viewed 368

So I have a login form which makes a POST request to app.js:

//app.js file
const express = require("express");
const ejs = require("ejs");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const { check } = require('express-validator');
const passport = require("passport");
const session = require("express-session");

const UserLogin = require("./middlwares/user-login");
const User = require("./database/Users");

const app = express();

//setting ejs
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static("public"));

//setting sessions and passport
app.use(session({
    secret: "Our little Secret for Sessions.",
    resave: false,
    saveUninitialized: false
}));

app.use(passport.initialize());
app.use(passport.session());

//Serializing and deserializing user for checking login status in cookie
passport.use(User.createStrategy());

passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());

app.post("/login", UserLogin);

and then the authentication happens in the user-login.js, which has Passport.authenticate(). This is working in another tutorial example where I am doing authentication in the main app.js itself. But here, the authenticate function is not executing. I don't understand why at all. I don't know how to investigate what happens when passport.authenticate() is executed. I tried going through the documentation but can't figure out why it's failing. Just trying to implement what I have learnt in my own project.

//user-login.js
const mongoose = require("mongoose");
const passport = require("passport");
const User = require("../database/Users");


module.exports = async (req, res) => {
    const user = new User({
        username: req.body.loginEmail,
        password: req.body.loginPassword
    });

    console.log(user.username + " and " + user.password);
    req.login(user, function(err){
        if (err) {
            console.log("user log-in triggered but error: " + err);
        } else {
            console.log("before authenticate");
            passport.authenticate("local")(req, res, function(){
            console.log("after authenticate");
                res.render("user-logged-in", {});
            });
            
        }
    });

Any help? Just started using stackOverflow, so apologies if the code dump is a bad way to ask a question. I also don't understand this syntax - passport.authenticate('local')(req, res, function(){});

1 Answers

Ok, I just realized the form making the POST request needs its fields to be named as username and password for the passport.authenticate() to work? That seems an odd sort of compulsion. In my HTML form, I had it named as loginEmail because that's also the label that I was using for end users; that's what was causing passport.authenticate() to fail.

It was not the file structure or some such obscure reason!

Related