护照:req.isAuthenticated() 不是一个函数,req.user 没有被护照设置
passport: req.isAuthenticated() is not a function and req.user is not being set by passport
我正在使用 MERN 堆栈创建一个 Web 应用程序,我想为其实现 google OAuth 和会话,我为此使用 'express-session' 和 'passport.js'。一切似乎都按预期工作,但我得到了 error: req.isAuthenticated isn't function
。此外, the value of req.user is "undefined"
但是,cookie 正在生成并成功存储在 MongoDB 中。我是节点和护照的新手,所以我无法找出问题所在。此外,以前针对同一错误提出的问题的解决方案对我不起作用。
这是错误
(node:10481) UnhandledPromiseRejectionWarning: TypeError: req.isAuthenticated is not a function
at addYear (/media/test/DATA/Dev/full-stack/projects/budget-app-backend/controllers/years.js:15:18)
at Layer.handle [as handle_request] (/media/test/DATA/Dev/full-stack/projects/budget-app-backend/node_modules/express/lib/router/layer.js:95:5)
at next (/media/test/DATA/Dev/full-stack/projects/budget-app-backend/node_modules/express/lib/router/route.js:137:13)
at Route.dispatch (/media/test/DATA/Dev/full-stack/projects/budget-app-backend/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/media/test/DATA/Dev/full-stack/projects/budget-app-backend/node_modules/express/lib/router/layer.js:95:5)
at /media/test/DATA/Dev/full-stack/projects/budget-app-backend/node_modules/express/lib/router/index.js:281:22
at Function.process_params (/media/test/DATA/Dev/full-stack/projects/budget-app-backend/node_modules/express/lib/router/index.js:341:12)
at next (/media/test/DATA/Dev/full-stack/projects/budget-app-backend/node_modules/express/lib/router/index.js:275:10)
at Function.handle (/media/test/DATA/Dev/full-stack/projects/budget-app-backend/node_modules/express/lib/router/index.js:174:3)
at router (/media/test/DATA/Dev/full-stack/projects/budget-app-backend/node_modules/express/lib/router/index.js:47:12)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:10481) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:10481) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
我也添加代码以供参考。
server.js
中的代码
const dotenv = require("dotenv");
dotenv.config();
const express = require("express");
const cors = require("cors");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const passport = require("passport");
const session = require("express-session");
const MongoStore = require("connect-mongo");
const authRouter = require("./routes/auth");
const Info = require("./models/Info");
const Transaction = require("./models/Transactions");
const recordsRouter = require("./routes/recordsRouter");
const { User, userSchema } = require("./models/Users");
const GoogleStrategy = require("passport-google-oauth20").Strategy;
const startDB = require("./models/db");
const app = express();
const PORT = process.env.PORT || 8000;
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(
cors({
origin: "http://localhost:3000",
methods: "GET,POST,PUT,DELETE",
credentials: true,
})
);
app.use(
session({
secret: "some random string",
resave: false,
saveUninitialized: false,
store: MongoStore.create({
mongoUrl: "mongodb://0.0.0.0:37017/budgetDB",
}),
})
);
startDB();
app.use("/auth", authRouter);
app.use("/dashboard", recordsRouter);
app.use(passport.initialize());
app.use(passport.session());
require("./passport")(passport);
app.listen(PORT, () => {
console.log(`Server started listening on port ${PORT}.....`);
});
passport.js
中的代码
const { User } = require("./models/Users");
const GoogleStrategy = require("passport-google-oauth20").Strategy;
module.exports = function (passport) {
passport.serializeUser((user, done) => {
console.log(`From passport.js serializeUser: ${user}`);
return done(null, user.id);
});
passport.deserializeUser((id, done) => {
User.findById(id, (err, user) => {
done(err, user);
});
});
passport.use(
new GoogleStrategy(
{
clientID: process.env.CLIENT_ID,
clientSecret: process.env.CLIENT_SECRET,
callbackURL: "http://localhost:8000/auth/google/callback",
userProfileURL: "https://www.googleapis.com/oauth2/v3/userinfo",
},
async (accessToken, refreshToken, profile, done) => {
const newUser = new User({
name: profile.displayName,
googleId: profile.id,
});
try {
const user = await User.findOne({ googleId: profile.id });
if (!user) {
user = await User.create(newUser);
}
return done(null, user);
} catch (err) {
console.log(`Error From 'passport.js': ${err}`);
return done(err);
}
}
)
);
};
auth.js
中的代码
const router = require("express").Router();
const passport = require("passport");
const CLIENT_URL = "http://localhost:3000";
router.get("/login/failed", (req, res) => {
console.log(res);
res.status(401).json({
message: "login failed",
});
});
router.get("/logout", (req, res) => {
req.logout();
res.redirect(CLIENT_URL);
});
router.get("/google", passport.authenticate("google", { scope: ["profile"] }));
router.get(
"/google/callback",
passport.authenticate("google", {
failureRedirect: "/login/failed",
successRedirect: CLIENT_URL + "/Dashboard",
})
);
module.exports = router;
用户模型中的代码
const mongoose = require("mongoose");
const userSchema = new mongoose.Schema({
name: String,
googleId: String,
});
const User = mongoose.model("User", userSchema);
module.exports = { User, userSchema };
中间件命令很重要。将 .use(passport...)
放在 .use(router...)
之前
我正在使用 MERN 堆栈创建一个 Web 应用程序,我想为其实现 google OAuth 和会话,我为此使用 'express-session' 和 'passport.js'。一切似乎都按预期工作,但我得到了 error: req.isAuthenticated isn't function
。此外, the value of req.user is "undefined"
但是,cookie 正在生成并成功存储在 MongoDB 中。我是节点和护照的新手,所以我无法找出问题所在。此外,以前针对同一错误提出的问题的解决方案对我不起作用。
这是错误
(node:10481) UnhandledPromiseRejectionWarning: TypeError: req.isAuthenticated is not a function
at addYear (/media/test/DATA/Dev/full-stack/projects/budget-app-backend/controllers/years.js:15:18)
at Layer.handle [as handle_request] (/media/test/DATA/Dev/full-stack/projects/budget-app-backend/node_modules/express/lib/router/layer.js:95:5)
at next (/media/test/DATA/Dev/full-stack/projects/budget-app-backend/node_modules/express/lib/router/route.js:137:13)
at Route.dispatch (/media/test/DATA/Dev/full-stack/projects/budget-app-backend/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/media/test/DATA/Dev/full-stack/projects/budget-app-backend/node_modules/express/lib/router/layer.js:95:5)
at /media/test/DATA/Dev/full-stack/projects/budget-app-backend/node_modules/express/lib/router/index.js:281:22
at Function.process_params (/media/test/DATA/Dev/full-stack/projects/budget-app-backend/node_modules/express/lib/router/index.js:341:12)
at next (/media/test/DATA/Dev/full-stack/projects/budget-app-backend/node_modules/express/lib/router/index.js:275:10)
at Function.handle (/media/test/DATA/Dev/full-stack/projects/budget-app-backend/node_modules/express/lib/router/index.js:174:3)
at router (/media/test/DATA/Dev/full-stack/projects/budget-app-backend/node_modules/express/lib/router/index.js:47:12)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:10481) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:10481) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
我也添加代码以供参考。
server.js
中的代码const dotenv = require("dotenv");
dotenv.config();
const express = require("express");
const cors = require("cors");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const passport = require("passport");
const session = require("express-session");
const MongoStore = require("connect-mongo");
const authRouter = require("./routes/auth");
const Info = require("./models/Info");
const Transaction = require("./models/Transactions");
const recordsRouter = require("./routes/recordsRouter");
const { User, userSchema } = require("./models/Users");
const GoogleStrategy = require("passport-google-oauth20").Strategy;
const startDB = require("./models/db");
const app = express();
const PORT = process.env.PORT || 8000;
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(
cors({
origin: "http://localhost:3000",
methods: "GET,POST,PUT,DELETE",
credentials: true,
})
);
app.use(
session({
secret: "some random string",
resave: false,
saveUninitialized: false,
store: MongoStore.create({
mongoUrl: "mongodb://0.0.0.0:37017/budgetDB",
}),
})
);
startDB();
app.use("/auth", authRouter);
app.use("/dashboard", recordsRouter);
app.use(passport.initialize());
app.use(passport.session());
require("./passport")(passport);
app.listen(PORT, () => {
console.log(`Server started listening on port ${PORT}.....`);
});
passport.js
中的代码const { User } = require("./models/Users");
const GoogleStrategy = require("passport-google-oauth20").Strategy;
module.exports = function (passport) {
passport.serializeUser((user, done) => {
console.log(`From passport.js serializeUser: ${user}`);
return done(null, user.id);
});
passport.deserializeUser((id, done) => {
User.findById(id, (err, user) => {
done(err, user);
});
});
passport.use(
new GoogleStrategy(
{
clientID: process.env.CLIENT_ID,
clientSecret: process.env.CLIENT_SECRET,
callbackURL: "http://localhost:8000/auth/google/callback",
userProfileURL: "https://www.googleapis.com/oauth2/v3/userinfo",
},
async (accessToken, refreshToken, profile, done) => {
const newUser = new User({
name: profile.displayName,
googleId: profile.id,
});
try {
const user = await User.findOne({ googleId: profile.id });
if (!user) {
user = await User.create(newUser);
}
return done(null, user);
} catch (err) {
console.log(`Error From 'passport.js': ${err}`);
return done(err);
}
}
)
);
};
auth.js
中的代码const router = require("express").Router();
const passport = require("passport");
const CLIENT_URL = "http://localhost:3000";
router.get("/login/failed", (req, res) => {
console.log(res);
res.status(401).json({
message: "login failed",
});
});
router.get("/logout", (req, res) => {
req.logout();
res.redirect(CLIENT_URL);
});
router.get("/google", passport.authenticate("google", { scope: ["profile"] }));
router.get(
"/google/callback",
passport.authenticate("google", {
failureRedirect: "/login/failed",
successRedirect: CLIENT_URL + "/Dashboard",
})
);
module.exports = router;
用户模型中的代码
const mongoose = require("mongoose");
const userSchema = new mongoose.Schema({
name: String,
googleId: String,
});
const User = mongoose.model("User", userSchema);
module.exports = { User, userSchema };
中间件命令很重要。将 .use(passport...)
放在 .use(router...)