Home > Net >  req.isAuthenticated always returns false
req.isAuthenticated always returns false

Time:06-26

    if (process.env.NODE_ENV !== "production") {
      require("dotenv").config();
    }
    
    const express = require("express");
    const app = express();
    const bcrypt = require("bcrypt");
    const passport = require("passport");
    const flash = require("express-flash");
    const session = require("express-session");
    
    const initializePassport = require("/sandbox/project/passport-config");
    
    initializePassport(
      passport,
      (email) => users.find((user) => user.email === email),
      (id) => users.find((user) => user.id === id)
    );
    
    const users = [];
    
    app.set("view-engine", "ejs");
    app.use(express.urlencoded({ extended: false }));
    app.use(flash());
    app.use(
      session({
        secret: process.env.SESSION_SECRET,
        resave: false,
        saveUninitialized: false
      })
    );
    app.use(passport.initialize());
    app.get("/", checkAuthenticated, (req, res) => {
      res.render("index.ejs", { name: "Saleh Khatri" });
    });
    
    app.get("/login", (req, res) => {
      res.render("login.ejs");
    });
    
    app.post(
      "/login",
      passport.authenticate("local", {
        successRedirect: "/",
        failureRedirect: "/login",
        failureFlash: true
      })
    );
    
    app.get("/register", (req, res) => {
      res.render("register.ejs");
    });
    
    app.post("/register", async (req, res) => {
      try {
        const hashedpassword = await bcrypt.hash(req.body.password, 10);
        users.push({
          id: Date.now().toString(),
          name: req.body.name,
          email: req.body.email,
          password: hashedpassword
        });
        res.redirect("/login");
      } catch {
        res.redirect("/register");
      }
    });
    
    function checkAuthenticated(req, res, next) {
      if (req.isAuthenticated()) {
        console.log("Authenticated");
        return next();
      } else {
        console.log("Not Authenticated");
        res.redirect("/login");
      }
    }
    
    app.listen(3000);
    
    
    
//even though i enter correct email and password it displays Not Authenticated
    
    passport-config code:
    const LocalStrategy = require("passport-local").Strategy;
    const bcrypt = require("bcrypt");
    
    function initialize(passport, getUserByEmail, getUserById) {
      const authenticateUser = async (email, password, done) => {
        const user = getUserByEmail(email);
        if (user == null) {
          return done(null, false, { message: "No user with that email" });
        }
        try {
          if (await bcrypt.compare(password, user.password)) {
            return done(null, user);
          } else {
            return done(null, false, { message: "password incorrect" });
          }
        } catch (e) {
          return done(e);
        }
      };
    
      passport.use(new LocalStrategy({ usernameField: "email" }, authenticateUser));
      passport.serializeUser((user, done) => done(null, user.id));
      passport.deserializeUser((id, done) => {
        return done(null, getUserById(id));
      });
    }`enter code here`
    
    module.exports = initialize;

//trying to debug it since hour and i am an absolute beginer so i have no idea //it return not authenticated evertimne even though i enter correct email and password

CodePudding user response:

First of all, this function is immediately executed once server starts listening on the port. Neither in function nor global scopes the user, email, id variables exist.

initializePassport(
  passport,
  email) => users.find((user) => user.email === email), // email == undefined, user == undefined
  id) => users.find((user) => user.id === id) // id == undefined
);

Secondly, you are trying to call an isAuthenticated() method, which isn't declared or expressed, on the request object.

function checkAuthenticated(req, res, next) {
   if (req.isAuthenticated()) { // req.isAuthenticated() == undefined, which is false
     console.log("Authenticated");
     return next();
   else {
     console.log("Not Authenticated"); // Therefore, this line is executed
     res.redirect("/login");
   }
}

I can not deliver the solution for you since I've no access to your code or I don't know which middleware you've created which affects request/response objects.

I hope, it helps you to debug the problem. Good luck!

  • Related