ensureAuthenticated midddleware not correctly authenticating

a user login successfully and redirected to profile was implemented with success.but, when i try to access a new route by requesting http://localhost:5000/user/admin/request/newAdmin route the authentication middleware responses with You are not authorized to view this page after login why is that???
server.js

require("dotenv").config();
const express = require("express");
const app = express();
// const flash = require("connect-flash");
const session = require("express-session");
const passport = require("passport");
const mongoose = require("mongoose");
const MongoStore = require("connect-mongo");
const cors = require("cors");

app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(cors());

// app.use(flash());
app.use(
  session({
    secret: process.env.SESSION_SECRET,
    resave: true,
    saveUninitialized: true,
    store: MongoStore.create({
      mongoUrl: process.env.DB,
      collection: "sessions",
    }),
    cookie: { secure: false, maxAge: 1000 * 60 * 60 * 24 * 3 },
  })
);

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

mongoose
  .connect(process.env.DB)
  .then(() => {
    console.log("DB connection successful");
  })
  .catch((err) => {
    console.log(`DB connection Error: ${err}`);
  });

  const userRouter = require("./routes/userRoutes");

  app.use("/user", userRouter);

const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
  console.log(`server is running on port ${PORT}`);
});

module.exports = app;

userRoutes.js

const router = require("express").Router();
const passport = require("passport");
const { ObjectID } = require("mongodb");
const LocalStrategy = require("passport-local");
const bcrypt = require("bcrypt");
const crypto = require("crypto");

const Token = require("../models/token");
const sendEmail = require("../utils/sendEmail");
const User = require("../models/userModel.js");

router.route("/register").post(
  (req, res, next) => {
    User.findOne({ fullName: req.body.fullName }, (err, user) => {
      if (err) {
        next(err);
      } else if (user) {
        res.json({ user: "user with that name already exists!" });
      } else {
        const {
          fullName,
          email,
          userType,
          department,
          stream,
          id,
          batch,
          phoneNumber,
          password,
        } = req.body;
        const hash = bcrypt.hashSync(password, 12);
        console.log(hash);
    if(userType === "Admin"){
      User.find({ userType: "Admin" }, (err, users) => {
        if (err) console.log(err);
            if(users.length === 0 ){
          
              const newUser = new User({
                fullName,
                email,
                userType,
                department,
                stream,
                id,
                batch,
                phoneNumber,
                password: hash,
              });
              newUser.save((err, data) => {
                if (err) console.log(err);
                next(null, data);
              });
            }else{
              const newUser = new User({
                fullName,
                email,
                userType,
                department,
                stream,
                id,
                batch,
                phoneNumber,
                password: hash,
                approved: false
              });
              newUser.save((err, data) => {
                if (err) console.log(err);
                next(null, data);
            })
          }
      })
    }else{
      const newUser = new User({
        fullName,
        email,
        userType,
        department,
        stream,
        id,
        batch,
        phoneNumber,
        password: hash,
      });
      newUser.save((err, data) => {
        if (err) console.log(err);
        next(null, data);
      });
    }
      }
    });
  },
  passport.authenticate("local", { failureRedirect: "/" }),
  (req, res, next) => {
    const userAuth = req.user.fullName;
    if (userAuth) {
      User.findOne({ fullName: userAuth }, (err, user) => {
        if (err) console.log(err);
        const userPriv = user.userType;
        if(userPriv === "Student"){
          return res.json({ user: user.fullName ,identity: {id: "Student"}});
        }
        else if(userPriv === "Admin"){
          
            if(user.approved){
          return res.json({ user: user.fullName , identity: {id: "Admin",approved: true} });
            }
            return res.json({ user: user.fullName , identity: {id: "Admin",approved: false} });
          
        }else{
  
          return res.json({ user: user.fullName , identity: {id: "Teacher"} });
        }
      });
    } else {
      res.sendStatus(401).json({ user: "Incorrect password or email" });
    }
  }
);

router.route("/login").post(passport.authenticate("local"), (req, res) => {
  const userAuth = req.user.fullName;
  console.log(req.user);
  if (userAuth) {
    User.findOne({ fullName: userAuth }, (err, user) => {
      if (err) console.log(err);
      const userPriv = user.userType;
      if(userPriv === "Student"){
        return res.json({ user: user.fullName ,identity: {id: "Student"}});
      }
      else if(userPriv === "Admin"){
        if(user.approved){
          return res.json({ user: user.fullName , identity: {id: "Admin",approved: true} });
            }
            return res.json({ user: user.fullName , identity: {id: "Admin",approved: false} });
          
      }else{

        return res.json({ user: user.fullName , identity: {id: "Teacher"} });
      }
    });
  } else {
    res.sendStatus(401).json({ user: "Incorrect password or email" });
  }
});

router.route("/admin/request/newAdmin").get(ensureAuthenticated,(req, res) => {
  User.find({userType: "Admin", approved: false},(err,users) => {
    if (err) console.log(err);
    res.json({users});
  })
});

router.route("/logout").get((req, res, next) => {
  req.logout(function (err) {
    if (err) {
      return next(err);
    }
    console.log("the user has logged out!");
    res.json({ user: "logout success!" });
  });
});

passport.serializeUser((user, done) => {
  done(null, user._id);
});

passport.deserializeUser((id, done) => {
  User.findOne({ _id: new ObjectID(id) }, (err, doc) => {
    done(null, doc);
  });
});

const customFields = {
  usernameField: "email",
};

passport.use(
  new LocalStrategy(customFields, (email, password, done) => {
    User.findOne({ email }, (err, user) => {
      console.log(`User ${user.email} attempted to log in.`);
      if (err) return done(err);
      if (!user) return done(null, false);
      if (!bcrypt.compareSync(password, user.password)) {
        return done(null, false);
      }
      return done(null, user);
    });
  })
);

function ensureAuthenticated(req, res, next) {
  if (req.isAuthenticated()) {
    return next();
  }
  console.log(req.isAuthenticated());
  console.log(req.user);

  res.redirect("/user/err");
}

router.route("/err").get((req,res) => {
  res.status(401).json({ msg: "You are not authorized to view this page" });
})
module.exports = router;

i was expecting for the ensureAuthenticated middleware to respond with authenticated because the user is logged in.but one thing i noticed is when i console logged req.user in the login route it set it to the current user object but in the ensureAuthenticated middleware it is undefined even if the user has not logged out.why is that?may be am i wrong when initializing the session and passport in server.js?

13 days and no reply at all? :unamused:

it is not from FCC,but it is similar to the challenges in advanced node on creating the passport authentication middleware.here is the github repository.

Hi @aynuman19 :wave:
It looks like there might be an issue with the way you are initializing Passport and the session middleware. The req.user property is set by Passport, so if it is undefined in the ensureAuthenticated middleware, it may indicate that Passport is not properly initializing or that the authentication process is not completing successfully.

Here’s a checklist of things to look for:

  1. Are you initializing the session middleware before Passport?
  2. Are you serializing and deserializing the user correctly in your Passport configuration?
  3. Are you properly using Passport’s login and isAuthenticated functions in your routes?
  4. Are you storing the session data correctly (e.g. in a database or in memory)?

If you can provide more context on how you’ve set up Passport and the session middleware in your server.js file, I can help you debug the issue more effectively.

sorry for the late reply,you can create an admin account by first logging out of the other account you have be registered i am guessing you registered by userType of Student because that is the default value set in the state in the form.so,after logging out you can register as an admin by selecting in the userType select section to admin.
note that the first admin account will have approved true value by default.so it has all the access an admin has but any other admin accounts after him will have approved false by default so that the first and other approved admins can approve it’s account until then it’s account is pending.so,inorder to see the issue i was encountering login as an admin(first account of admin) and go to profile route(by default it will go to profile route after either registering or logging) then click on the side bar that say new admin request and open the console and you will see Unauthorized message because if U see in the newAdmin.jsx i am requesting server request to the route http://localhost:5000/user/admin/request/newAdmin and in the server folder in userRoutes.js @ line 146 i am calling the ensureAuthenticated middleware which is defined at the end of the file.

yes as you can see in the server.js file above

yes in the userRoutes.js file from line 217 almost at the end you can see i have set up those

yes in a database.when i initialize the session middleware you can see in the server.js file above i have properly set the store key as follows

and it will be saved in the database i have checked it may be i am not sure whether it is good to say false or true to the keys

yes i have used passport.authenticate(“local”) middleware both in the /register and /login routes and req.isAuthenticated() in the ensureAuthenticated middleware and the latter was causing a problem as i have mention.

hi,is there Any updates?

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.