passport-local throws 401 unauthorised even on correct credentials

23 Views Asked by At

I have this code below, and the routes are correctly set up. However when I provide the login details, even when they are correct, an error of 401 unauthorised is still sent as the response. Please what am I doing wrong? I am using the mongdb driver for Node.js (no mongoose.js) here with react.js and passport-local. Thank you!!!

import express from "express";
import passport from "passport";
import LocalStrategy from "passport-local";
import bcrypt from "bcrypt";
import client from "../db/client.js";

passport.use(
  new LocalStrategy(
    {
      usernameField: "emailOrPhone",
      passwordField: "password",
      session: false,
    },
    async (emailOrPhone, password, done) => {
      try {
        const database = client.db("test");
        const collection = database.collection("users");

        const user =
          (await collection.findOne({ "email address": emailOrPhone })) ||
          (await collection.findOne({ "phone number": emailOrPhone }));

        if (!user) {
          return done(null, false);
        }

        if (!(await bcrypt.compare(password, user.password))) {
          return done(null, false);
        }

        return done(null, user);
      } catch (err) {
        return done(err);
      }
    }
  )
);

const router = express.Router();

router.post("/", passport.authenticate("local"));

export default router;
0

There are 0 best solutions below