所以,我一切正常,直到路由似乎没有收到我发送给用户的数据为止。但是,如果console.log位于护照内,它将吐出正确的信息。所以这是我的护照代码,大部分情况下有效:
const LocalStrategy = require('passport-local').Strategy;
const db = require('mongodb');
const bcrypt = require('bcryptjs');
const config = require('./config');
module.exports = async (passport) => {
// =========================================================================
// passport session setup ==================================================
// =========================================================================
// used to serialize the user for the session
passport.serializeUser((user, done) => {
done(null, user._id);
});
// used to deserialize the user
passport.deserializeUser(async(id, done) => {
let userData = await userDb().findOne({ '_id': id});
done(null, userData);
});
// Local Strategy login
passport.use('local-login', new LocalStrategy({
usernameField: 'email',
passReqToCallback: true,
}, async (req, username, password, done) => {
console.log('Pulled up: ' + username);
let userDb = await usersDb();
let userData = await userDb.findOne({ 'email': username})
// Check if user exists
if (userData === null) {
console.log('User doesn\'t exist');
return Promise.reject('Email or password incorrect.');
} else {
// if user exists check password
let passCheck = await bcrypt.compareSync(password, userData.password);
if (passCheck) {
console.log('Password Correct');
return done(null, userData);
} else {
// if password is wrong
console.log('Password incorrect');
return Promise.reject('Email or password incorrect.');
}
}
}));
// DB collection
async function usersDb() {
const client = await db.MongoClient.connect(
config.database,
{
useNewUrlParser: true
}
);
return client.db('kog').collection('users');
}
};
这是登录路径:
router.post('/login',
passport.authenticate('local-login', {
successRedirect: '/game',
failureRedirect: '/',
}), (req, res) => {
});
但是我的问题在这里:
// Get game route
app.get('/game', async (req, res) => {
if (req.user) {
res.render('game');
} else {
console.log('Forced redirect');
res.redirect('/');
}
});
想到了可能有问题的另一个障碍:
app.get('*', async (req, res, next) => {
res.locals.user = await req.user || null;
next();
});
无论我做什么,我似乎都无法获得路由检查来提取用户数据。我不确定我在哪里出问题了,因为到那时为止一切都可行。我将成功“登录”,但即使所有工作正常,也会被强制重定向到“ /”。
我可以肯定这是我可能没有正确处理异步/等待内容的事实,但是我不确定在哪里出现问题。
答案 0 :(得分:0)
我认为您不见了:
passport.authenticate('local')
哪个会触发您的passport.js
文件localStrategy
。不确定如何运行护照文件来检查控制台。
有关更多信息,请参见:http://www.passportjs.org/docs/authenticate/