Handle login errors with passport and express without reloading page

Viewed 23

I want to log in user using passport, but I want also to catch errors while login, when user doesn't exist or when password is incorrect. Page shouldn't reload if user has inserted incorrect data, so I think, best way to do this is use fetch API on client side js. If is it possible, manually send data to client. Maybe it can be done with flash?

My passport config:

const bcrypt = require("bcrypt");
const dbUtil = require("./../utils/dbUtil");
const LocalStrategy = require("passport-local").Strategy;
 
function initialize(passport) {
  function authenticateUser(mail, password, cb) {
    console.log("authenticate");
    dbUtil
      .fetchAccount(mail)
      .then(async (result) => {
        const user = result[0];
        if (user == null)
          return cb(null, false, { message: "user does not exist" }); 
        const passwordsMatch = await bcrypt.compare(password, user.PASSWORD);
        if (passwordsMatch) {
          return cb(null, user);
        } else {
          return cb(null, false, { message: "incorrect password" });
        }
      })
      .catch((err) => {
        return cb(err);
      });
  }
  passport.use(
    new LocalStrategy(
      { usernameField: "mail", passwordField: "password" },
      authenticateUser
    )
  );
 
  passport.serializeUser(function (user, cb) {
    process.nextTick(function () {
      cb(null, {
        id: user.ID,
        nickname: user.USERNAME,
        mail: user.MAIL,
        profile_img: user.PROFILE_PICTURE,
        profile_color: user.PROFILE_COLOR,
        registration_date: user.REGISTRATION_DATE,
      });
    });
  });
 
  passport.deserializeUser(function (user, cb) {
    process.nextTick(function () {
      return cb(null, user);
    });
  });
}
function checkAuthenticated(req, res, next) {
  if (req.isAuthenticated()) {
    return next();
  }
 
  res.redirect("/login");
}
 
function checkNotAuthenticated(req, res, next) {
  if (req.isAuthenticated()) {
    return res.redirect("/");
  }
  next();
}
module.exports = { initialize, checkAuthenticated, checkNotAuthenticated };

and here is router for signup:

const express = require("express");
let router = express.Router();
const signUtil = require("./../utils/signUtil");
const validator = require("./../utils/validateUtil");
const passportConfig = require("./../config/passport");
const passport = require("passport");
 
router
  .route("/login")
  .get(passportConfig.checkNotAuthenticated, (req, res, next) => {
    res.render("signIn");
  })
  .post(
    passport.authenticate("local", {
      successRedirect: "/",
      failureRedirect: "/login",
      failureFlash: true,
    })
  );
 
router
  .route("/logout")
  .get(passportConfig.checkAuthenticated, function (req, res) {
    req.logout((err) => {
      if (err) throw err;
      res.redirect("/login");
    });
  });
module.exports = router;

Used middlewares:

├── bcrypt@5.0.1
├── body-parser@1.20.0
├── connect-sqlite3@0.9.13
├── cookie-parser@1.4.6
├── dotenv@16.0.1
├── ejs@3.1.8
├── express-flash@0.0.2
├── express-session@1.17.3
├── express@4.18.1
├── method-override@3.0.0
├── nodemon@2.0.16
├── passport-local@1.0.0
├── passport@0.6.0
├── path@0.12.7
├── sass@1.52.3
└── sqlite3@5.0.8

Now it works fine, but without error catching

0 Answers
Related