我正在尝试在某人登录时将用户分配给cookie,但看起来护照没有将数据分配给cookie。在下面可以找到代码:
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(cookieParser());
app.use(bodyParser.json());
app.use(passport.initialize());
//Use session
app.use(passport.session({ secret: '=Mx;D5F}t&iJZ&w-g;FLK:%QavZgZt', cookie: { maxAge: 0 }, resave: true, saveUninitialized: true }))
app.use(express.static('server/public'));
//Set view engine
app.set('views', 'server/views')
app.set('view engine', 'pug');
//Set passport local strategy
passport.use(new LocalStrategy({ usernameField: "email" },
function (email, password, done) {
User.findOne({ 'email': email }, async function (err, user) {
console.log('user requested password caught in passport: ', password);
if (err) { return done(err); }
if (!user) {
return done(null, false, console.log('Wrong username'));
}
return await user.validatePassword(password, function (err, result) {
if (err || !result) return done(null, false, console.log('Wrong Password'));
return done(null, user);
})
});
}
));
// serialize user object
passport.serializeUser(function (user, done) {
done(null, user.id);
});
// deserialize user object
passport.deserializeUser(function (id, done) {
User.findById(id, function (err, user) {
done(err, user);
})
});
这是登录路径:
//Route for user login
app.post('/auth/local/signin',
function (req, res, next) {
passport.authenticate('local', function (err, user, info) {
console.log(err);
console.log(user);
if (err) {
console.log('passport.authenticate: error')
} else if (!user) {
console.log('passport.authenticate: user')
} else {
console.log('next handler')
console.log('Cookie assigned: ' + req.user)
return res.redirect('/dashboard')
}
return res.redirect('/login')
})(req, res, next)
}
)
如您所见,我尝试登录req.user,这给了我未定义的信息。
但是,console.log(user)却从数据库中将我带回了该用户。