我正在使用护照,护照-谷歌-oauth20 20编写身份验证Nodejs
一切都是工作,但问题是,现在我想通过域验证用户的电子邮件。我的系统只是允许电子邮件与域@framgia.com可以登录到。如果没有,请向用户发回一条消息。
我的密码是:
const passport = require('passport');
const GoogleStrategy = require('passport-google-oauth20').Strategy;
const mongoose = require('mongoose');
const keys = require('../config/keys');
const User = mongoose.model('users');
passport.serializeUser((user, done) => {
done(null, user.id);
});
passport.deserializeUser((id, done) => {
User.findById(id).then(user => {
done(null, user);
})
});
passport.use(
new GoogleStrategy(
{
clientID: keys.googleClientID,
clientSecret: keys.googleClientSecret,
callbackURL: '/auth/google/callback',
},
async (accessToken, refreshToken, profile, done) => {
const existingUser = await User.findOne({ googleId: profile.id });
if (existingUser) {
return done(null, existingUser);
}
if (!profile._json.domain || profile._json.domain !== 'framgia.com') {
return done(null, {error: 'Not allow access!'});
}
const user = await new User({
googleId: profile.id,
email: profile.emails[0].value,
name: profile.displayName,
avatar: profile.photos[0].value,
}).save();
done(null, user);
},
),
);我在写这样的逻辑代码:
if (!profile._json.domain || profile._json.domain !== 'framgia.com') {
return done(null, {error: 'Not allow access!'});
}但我认为这是行不通的,但我不知道如何处理错误,并将消息发送回用户。
我的路线:
const passport = require('passport');
module.exports = (app) => {
app.get(
'/auth/google',
passport.authenticate('google', {
scope: ['profile', 'email'],
}),
);
app.get(
'/auth/google/callback',
passport.authenticate('google', { failureRedirect: '/login' }),
(req, res) => {
// Successful authentication, redirect home.
res.redirect('/');
},
);
};如何处理错误并重定向到带有消息的/error路由?
任何想法都将不胜感激,谢谢。
发布于 2018-09-27 05:17:07
首先,如果您只想在电子邮件有特定域的情况下返回用户,则需要将域检查逻辑放在findOne()之前。根据当前的逻辑,如果您找到了一个用户,它将直接返回它,而不检查电子邮件域。
//check email domain before finding the user
if (!profile._json.domain || profile._json.domain !== 'framgia.com') {
return done(null, {error: 'Not allow access!'});
}
const existingUser = await User.findOne({ googleId: profile.id });
if (existingUser) {
return done(null, existingUser);
}根据护照js文件,http://www.passportjs.org/docs/configure/ (检查确认回调部分)
可以提供一条额外的信息消息来指示失败的原因。这对于显示提示用户再次尝试的闪存消息非常有用。
因此,如果域不匹配,则应返回如下错误
return done(null, false, { message: 'Not allow access!' });https://stackoverflow.com/questions/52529494
复制相似问题