如何在不创建空字符串的情况下存储多个Outh2 ID



我正在尝试创建一个基本的应用程序,在那里你可以通过电子邮件/密码或使用谷歌或Facebook Oauth2注册,将必要的信息保存在mongoDB中。当你试图从多个谷歌或脸书账户访问该应用程序时,就会出现问题。(500内部服务器错误(我知道问题是,通过使用Oauth2,我创建了一个空/null字符串,由于索引(我不完全理解(,在mongoDB中会导致错误。请看一下我的代码,我去掉了不必要的行,使它更短。以下是数据库的屏幕截图:数据库屏幕截图

const userSchema = new mongoose.Schema({
email: String,
password: String,
googleId: String,
facebookId: String,
secret: Array
});
userSchema.plugin(passportLocalMongoose);
userSchema.plugin(findOrCreate);
const User = new mongoose.model("User", userSchema);
passport.use(User.createStrategy());
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user) {
done(err, user);
});
});
passport.use(new GoogleStrategy({
clientID: process.env.CLIENT_ID,
clientSecret: process.env.CLIENT_SECRET,
callbackURL: "https://app-secret.herokuapp.com/auth/google/secrets",
userProfileURL: "https://www.googleapis.com/oauth2/v3/userinfo"
},
function(accessToken, refreshToken, profile, cb) {
// console.log(profile);
User.findOrCreate({
googleId: profile.id
}, function(err, user) {
return cb(err, user);
});
}
));
passport.use(new FacebookStrategy({
clientID: process.env.FACEBOOK_APP_ID,
clientSecret: process.env.FACEBOOK_APP_SECRET,
callbackURL: "https://app-secret.herokuapp.com/auth/facebook"
},
function(accessToken, refreshToken, profile, cb) {
User.findOrCreate({
facebookId: profile.id
}, function(err, user) {
return cb(err, user);
});
}
));
app.get("/auth/google",
passport.authenticate('google', {
scope: ["profile"]
})
);
app.get("/auth/google/secrets",
passport.authenticate('google', {
failureRedirect: "/login"
}),
function(req, res) {
// Successful authentication, redirect home.
res.redirect('/secrets');
});
app.get('/auth/facebook',
passport.authenticate('facebook'));
app.get('/auth/facebook/secrets',
passport.authenticate('facebook', {
failureRedirect: '/login'
}),
function(req, res) {
// Successful authentication, redirect home.
res.redirect('/secrets');
});
app.post("/register", function(req, res) {
User.register({
username: req.body.username <----i assume this is the issue as using Oauth2 it will be null
}, req.body.password, function(err, user) {
if (err) {
console.log(err);
res.redirect("/register")
} else {
passport.authenticate("local")(req, res, function() {
res.redirect("/secrets")
})
}
})
});

尽管它不是一个"优雅的";但最终我克服了为用户名分配变量的问题,即使它们的t need to have one as they were using Oauth.. Like this the string won不是空的或null的,所以mongoDB最终允许更多用户从谷歌和脸书注册。

相关内容

最新更新