我使用async / await实现了护照本地策略,如下所示
const strategy = new LocalStrategy(
async(username, password, done) => {
try {
// Find the user given the username
const user = await User.findOne({ username });
// If not, send info
if (!user) {
return done(null, false, {
success: false,
message: 'User not found'
})
}
// Check if the password is correct
const isMatch = await user.isValidPassword(password);
// If not, send info
if (!isMatch) {
return done(null, false, {
success: false,
message: 'Invalid Password'
});
}
// Otherwise, return the user
done(null, user);
} catch (error) {
done(error, false);
}
}
);
passport.use(strategy);
使用以下代码在路线中实施自定义回调。
router.post('/login', async(req, res, next) => {
const { receivedUser, information } = await passport.authenticate('local');
// If a user is found
if (receivedUser) {
res.status(200).json({
success: true,
message: 'Authentication Successful'
});
} else {
// If user is not found
res.status(401).json(information);
}
};
);
以上自定义回调实现中存在错误,因为receiveUser和信息是“未定义的”。如何使用async / await更改上面的自定义回调以删除错误?
推荐文档:
http://passportjs.org/docs/configure
http://passportjs.org/docs/username-password