【发布时间】:2019-08-28 04:10:16
【问题描述】:
我刚开始使用 express 和 passport.js,并且在使用护照进行身份验证期间难以显示错误消息
当用户成功通过身份验证时,我可以重定向用户并且一切都很好,但是,如果使用不同的策略对同一电子邮件进行身份验证,我想显示一条消息,说明给定的电子邮件已经与不同的策略相关联.
这是我的 auth-routes.js
router.get(
'/google',
passport.authenticate('google', {scope: ['email', 'profile']})
);
router.get('/google/redirect', passport.authenticate('google', { successRedirect: '/protected/'}));
这是我的 authController.js
passport.use(
new GoogleStrategy(
{
callbackURL: cbUrl,
clientID: process.env.GOOGLE_KEY,
clientSecret: process.env.GOOGLE_SECRET
},
(accessToken, refreshToken, profile, done) => verify(profile, done, 'Google')
)
);
function verify(profile, done, provider) {
User.findOne({
email: profile.email || profile.emails[0].value
}).then((currentUser) => {
if (currentUser) {
if (currentUser.provider !== provider)
return done(null, false, {message: `Login with ${provider} failed, this account is already associated with ${currentUser.provider}` });
else
return done(null, currentUser);
} else {
new User({
name: profile.displayName,
email: profile.email || profile.emails[0].value,
userId: profile.id,
provider: provider
}).save().then((newUser) => {
return done(null, newUser);
});
}
return done('Something went wrong!');
});
}
总结一下,如果我使用 Google oauth 使用电子邮件 jhon.doe@gmail.com 注册了一个帐户,然后尝试使用 jhon.doe@gmail.com 登录或注册,但这次使用 Facebook oauth,我想返回一条消息并在我的登录页面上显示该消息。
【问题讨论】:
标签: express passport.js