req.isAuthenticated() doesn’t work as it should

I am trying to implement passport. What i am trying to achive is only logged in users will be able to access /create route and create new posts.
I imported necessary libraries.

import passport from "passport";
import localStrategy from "passport-local";
import session from "express-session";
import connectPgSimple from 'connect-pg-simple';

I implement passpor logic.

 passport.use(new localStrategy(async function verify(username, password, cb) {
    try {
      const result = await db.query(`SELECT * FROM loginDetail WHERE username = $1`, [username]);
      if (result.rows.length === 0) {
        return cb(null, false, { message: "Incorrect username or password" });
      }
      const row = result.rows[0];
      bcrypt.compare(password, row.password, (err, result) => {
        if (err) {
          console.error("Error comparing passwords:", err);
          return cb(null, false, { message: "Failed to compare passwords" });
        } else if (result) {
          // Passwords match, user is authorized
          return cb(null, row);
        } else {
          // Passwords don't match, render login page with error message
          return cb(null, false, { message: "Invalid credentials. Please try again." });
        }
      });
    } catch (err) {
      return cb(err);
    }
  }));

  app.use(
    session({
      secret: 'keyboard cat',
      resave: false,
      saveUninitialized: false,
      cookie: { secure: true }
    })
  ); 
  passport.serializeUser(function(user, cb) {
    cb(null, user.id);
  });
  
  // passport.deserializeUser(function(id, cb) {
  //   // Retrieve user from the database based on the provided ID
  //   // Example assuming you have a `User` model:
  //   db.query('SELECT * FROM users WHERE id = $1', [id], function(err, result) {
  //     if (err) { return cb(err); }
  //     cb(null, user);
  //   });
  // });
  passport.deserializeUser(function(id, done) {
    db.query('SELECT * FROM loginDetail WHERE id = $1', [id], function(err, result) {
      if(err)
        return done(err, user);
      if(result.rows.length > 0){
        const user = result.rows[0];
        done(null, user)
      }else{done(null, false)}
    });
  });
  app.use(passport.initialize());
  app.use(passport.session());

app.post("/login",passport.authenticate('local', { failureRedirect: '/login',successRedirect:"/" }), async (req, res) => {
  
});

I create ensureAuthenticated to make sure only loggedin users will be able to access /create route.

function ensureAuthenticated(req, res, next) {
  if (req.isAuthenticated()) {
    // If the user is authenticated, allow the request to proceed
    return next();
  } else {
    // If the user is not authenticated, redirect to the login page
    res.redirect("/login");
  }
}

app.get("/create",ensureAuthenticated, (req, res) => {
  res.render("create.ejs");
});

app.post("/create",ensureAuthenticated, async (req, res) => {
  
    const result = await db.query("SELECT MAX(id) AS max_id FROM posts");
    const maxId = result.rows[0].max_id || 0; // If no posts exist, set maxId to 0

    // Increment the maximum ID by one to generate a new unique ID
    const newId = maxId + 1;
    const post = {
      id: newId,
      author: req.body.author,
      title: req.body.title,
      content: req.body.content,
    };

    const postPush = await db.query(
      "INSERT INTO posts (id,author,title,content) VALUES($1,$2,$3,$4) RETURNING *;",
      [post.id, post.author, post.title, post.content]
    );

  
});

I implemented passport logic and created function ensureAuthenticated to allow only loggedin users to access and create post. I successfully login and be redirected to /.

New contributor

user23773270 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật