我在这两天里已经呆了八个小时,我很沮丧。
我将对其进行细分,但是正在发生的是本地策略本身并未真正运行(该策略内部的控制台日志未记录)。我收到的错误是:错误:无法将用户序列化为会话,但这似乎是因为传递给passport.SerializeUser的值是 false 。
我的Facebook和Twitter登录都可以工作并创建cookie,所以我认为这与序列化或解析无关,它实际上不是在查询数据库的本地策略,因此倾向于序列化一个false布尔值。
我的服务器文件如下:
const express = require('express');
const session = require("express-session");
const cors = require("cors");
const logger = require("morgan");
const mongoose = require("mongoose");
const cookieParser = require("cookie-parser");
const passport = require("passport");
const cookieSession = require("cookie-session");
const MongoStore = require('connect-mongo')(session);
const routes = require("./routes");
const passportSetupTwitter = require("./config/passport/twitter");
const passportSetupFacebook = require("./config/passport/facebook")
const passportSetupLocal = require("./config/passport/local")
const keys = require("./config/passport/twitter");
const app = express();
const PORT = process.env.PORT || 8080;
app.use(logger("dev"));
// Sets up the Express app to handle data parsing
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(cookieSession({
name: 'session',
keys: ['key1', 'key2'],
maxAge: 24 * 60 * 60 * 100
}));
//initialize passport
app.use(passport.initialize());
//deserialize cookies
app.use(passport.session());
//Sets up cors to allow client requests
app.use(
cors({
origin: ["http://localhost:3000"],
methods: "GET,HEAD,PUT,PATCH,POST,DELETE",
credentials: true//allow session cookie to pass through
})
);
// app.use(cors({
// origin: ["https://mgr-talent.herokuapp.com"]
// }));
app.use(routes);
mongoose.connect(
process.env.MONGODB_URI || "mongodb://localhost/mgr",
{
useNewUrlParser: true,
useUnifiedTopology: true
});
app.listen(PORT, function () {
console.log('App listening on PORT ' + PORT);
});
我的路线如下:
//Local login route
// '/auth/login'
router.post('/login',(req, res, next) => {
passport.authenticate('local', (error, user, info) => {
if (error) {
const statusCode = error.statusCode || 500;
return res.status(statusCode).json(error)
}
req.login(user, (error) => {
if (error) {
console.log("2nd ERROR: ",error);//THIS IS THE ERROR THAT'S LOGGING TO THE CONSOLE
const statusCode = error.statusCode || 500;
return res.status(statusCode).json(error)
}
return res.redirect(CLIENT_HOME_PAGE_URL)
})
})(req, res, next);
});
我的策略文件如下:
const passport = require("passport");
const LocalStrategy = require("passport-local").Strategy;
const User = require("../../models/User");
passport.use('local',
new LocalStrategy(function (email, password, done) {
console.log('ASGGQERG');//THIS IS NOT LOGGING
User.findOne({ email: email }, function (err, user) {
console.log(user);//THIS IS NOT LOGGING
if (err) {
return done(err);
}
if (!user) {
return done(null, false);
}
if (user.password != password) {
return done(null, false);
}
return done(null, user);
});
})
);
// serialize the user.id to save in the cookie session
// so the browser will remember the user when login
passport.serializeUser((user, done) => {
console.log(user); //LOGS false
done(null, user);
});
// deserialize the cookieUserId to user in the database
passport.deserializeUser((id, done) => {
User.findById(id)
.then(user => {
done(null, user);
})
.catch(e => {
done(new Error("Failed to deserialize a user"));
});
});