Akhil-Sharma02
Akhil-Sharma02

Reputation: 93

req.user only having username field

I am new to passport js. While using it when I console.log req.user it only shows username field. It always gives output as { username: 'a' }. It does not show any other field like email.

Here is the index.js file:

const express = require("express");
const app = express();
const mongoose = require("mongoose");
const Routes = require("./api/Routes");
const session = require("express-session");
const MongoDBStore = require("connect-mongodb-session")(session);
const passport = require("passport");
const http = require("http");
const cors = require("cors");
const cookieParser = require("cookie-parser");
require("dotenv").config();

mongoose
    .connect(process.env.MONGO_URL)
    .then(() => {
        console.log("DB Connected");
    })
    .catch((err) => {
        console.log(err);
    });

app.use(express.json());
app.use(express.urlencoded({ extended: true }));
if (process.env.NODE_ENV === "production") {
    app.set("trust proxy", 1);
}
app.use(
    cors({
        origin: "http://localhost:3000",
        credentials: true,
    })
);
const storeMongo = new MongoDBStore({
    uri: process.env.MONGO_URL,
    collection: "mySessions",
});
app.use(
    session({
        name: "Test Cookie",
        secret: "ThisIsASecret",
        resave: true,
        saveUninitialized: true,
        proxy: process.env.NODE_ENV === "production",
        cookie: {
            sameSite: process.env.NODE_ENV === "production" ? "none" : "lax",
            maxAge: 1000 * 60 * 100,
            secure: process.env.NODE_ENV === "production",
        },
        store: storeMongo,
    })
);
app.use(cookieParser());
app.use(passport.initialize());
app.use(passport.session());
require("./passport-config")(passport);
app.use(Routes);
const server = http.createServer(app);
const port = process.env.PORT || 8000;
server.listen(port, () => {
    console.log(`Server running at port ${port}`);
});

Here is the passport-config.js file:

const User = require("./models/User");
const bcrypt = require("bcryptjs");
const localStrategy = require("passport-local").Strategy;

module.exports = function (passport) {
    passport.use(
        new localStrategy((username, password, done) => {
            User.findOne({ username: username }, (err, user) => {
                if (err) throw err;
                if (!user) return done(null, false);
                bcrypt.compare(password, user.password, (err, result) => {
                    if (err) throw err;
                    if (result === true) {
                        return done(null, user);
                    } else {
                        return done(null, false);
                    }
                });
            });
        })
    );

    passport.serializeUser((user, cb) => {
        console.log("in serialize");
        console.log(user);
        cb(null, user.id);
    });
    passport.deserializeUser((id, cb) => {
        User.findOne({ _id: id }, (err, user) => {
            const userInformation = {
                username: user.username,
            };
            cb(err, userInformation);
        });
    });
};

Here is the user model:

const mongoose = require("mongoose");
const userSchema = new mongoose.Schema(
    {
        username: {
            type: String,
            required: true,
        },
        password: {
            type: String,
            required: true,
        },
        email: {
            type: String,
            trim: true,
            required: true,
        },
    },
    {
        timestamps: true,
    }
);
const User = mongoose.model("User", userSchema);
module.exports = User;

Can anyone tell me what is wrong with my code.

Upvotes: 0

Views: 827

Answers (1)

lpizzinidev
lpizzinidev

Reputation: 13274

If you want to add other properties to req.user you should specify them in the deserializeUser function:

  passport.deserializeUser((id, cb) => {
    User.findOne({ _id: id }, (err, user) => {
      
      const userInformation = {
        username: user.username,
        email: user.email,
        // Add other fields if you need to...
      };
      cb(err, userInformation);
    });
  });

You can find a descriptive explanation of how serializeUser and deserializeUser work on this answer.

Upvotes: 1

Related Questions