我正在尝试在测试时显示错误消息,以查看与护照facebook策略关联的电子邮件地址是否已存在于数据库中。
这是我的代码:
// callback route for facebook to redirect to
router.get('/facebook/redirect', passport.authenticate('facebook'), (req, res) => {
res.redirect('/profile/');
});
// Facebook Strategy
passport.use(
new FacebookStrategy({
clientID: keys.facebook.clientID,
clientSecret: keys.facebook.clientSecret,
callbackURL: '/auth/facebook/redirect',
profileFields: ['id', 'email', 'displayName', 'photos']
}, (err, accessToken, refreshToken, profile, done) => {
User.findOne({ email: profile.emails[0].value }).then((response) => {
if(response) {
console.log('Email already exists.'); // This is where I get my response
} else {
User.findOne({
facebookID: profile.id
}).then((currentUser) => {
if(currentUser) {
done(null, currentUser);
} else {
new User({
name: profile.displayName,
username: profile.displayName + ' Facebook',
facebookID: profile.id,
email: profile.emails[0].value,
avatar: profile.photos ? profile.photos[0].value : '/img/faces/unknown-user-pic.jpg'
}).save().then((newUser) => {
done(null, newUser);
});
}
})
}
})
})
);
如果电子邮件已存在,如何在登录页面上向用户显示错误消息?
答案 0 :(得分:0)
我设法找到了解决方案。我添加了一个故障重定向到我的facebook回调:
// callback route for facebook to redirect to
router.get('/facebook/redirect', passport.authenticate('facebook', {
successRedirect: '/profile/',
failureRedirect: '/auth/login',
failureFlash: true
}), (req, res) => {
res.redirect('/profile/');
});
然后返回null,false并显示错误消息:
passport.use(
new FacebookStrategy({
clientID: keys.facebook.clientID,
clientSecret: keys.facebook.clientSecret,
callbackURL: '/auth/facebook/redirect',
profileFields: ['id', 'email', 'displayName', 'picture.type(large)']
}, (err, accessToken, refreshToken, profile, done) => {
User.findOne({
facebookID: profile.id
}).then((currentUser) => {
if (currentUser) {
done(null, currentUser);
} else {
User.findOne({ email: profile.emails[0].value }).then((response) => {
if (response) {
done(null, false, {message: "Email already exists"}); // <-- Where I return the callback
} else {
new User({
name: profile.displayName,
username: profile.displayName + ' Facebook',
facebookID: profile.id,
email: profile.emails[0].value,
avatar: profile.photos ? profile.photos[0].value : '/img/faces/unknown-user-pic.jpg'
}).save().then((newUser) => {
done(null, newUser);
});
}
})
}
})
})
);
我希望这可以帮助其他遇到同样问题的人:)