req.user只有用户名字段

发布于 2025-02-07 01:36:41 字数 3585 浏览 0 评论 0原文

我是护照JS的新手。当我委托时使用它时,它仅显示用户名字段。它始终将输出作为{用户名:'a'}。它没有显示任何其他字段,例如电子邮件。

这是index.js文件:

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}`);
});

这是Passport-config.js文件:

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);
        });
    });
};

这是用户模型:

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;

任何人都可以告诉我我的代码有什么问题。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

各自安好 2025-02-14 01:36:41

如果要将其他属性添加到req.user中,则应在deserializeuser函数中指定它们:

  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);
    });
  });

您可以找到serializeizeuser的描述性说明。 deserializeuser在此答案

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文