【发布时间】:2021-09-05 03:44:22
【问题描述】:
所以,我成功地使用节点包 passport-google-oauth20 在我正在编写的测试 Web 应用程序上对用户进行身份验证...这是代码:
passport.use(
new GoogleStrategy(
{
clientID: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
callbackURL: 'http://localhost:3000/auth/google/secrets',
userProfileURL: 'https://www.googleapis.com/oauth2/v3/userinfo'
},
(accessToken, refreshToken, profile, done) => {
User.findOne({ googleId: profile.id }).then(currentUser => {
if (currentUser) {
//if we already have a record with the given profile ID
done(null, currentUser);
} else {
//if not, create a new user
new User({
googleId: profile.id
})
.save()
.then(newUser => {
done(null, newUser);
});
}
});
}
)
);
但是,当我导入并尝试使用节点包 passport-facebook 时,如下所示:
passport.use(
new FacebookStrategy(
{
clientID: process.env.FACEBOOK_APP_ID,
clientSecret: process.env.FACEBOOK_APP_SECRET,
callbackURL: 'http://localhost:3000/auth/facebook/secrets'
},
(accessToken, refreshToken, profile, done) => {
User.findOne({ facebookId: profile.id }).then(currentUser => {
if (currentUser) {
//if we already have a record with the given profile ID
done(null, currentUser);
} else {
//if not, create a new user
new User({
facebookId: profile.id
})
.save()
.then(newUser => {
done(null, newUser);
});
}
});
}
)
);
我遇到了问题。在我的应用程序中,我到达了“使用 facebook 登录”屏幕。但是,应用程序只是挂起并给我一个错误而不是重定向。这是错误:
UnhandledPromiseRejectionWarning: MongoError: E11000 duplicate key error collection: userDB.users index: username_1 dup key: { username: null }
有没有人在使用 passport.js 身份验证策略时遇到过这种情况?
【问题讨论】:
-
您正在从 google 添加用户,并将用户名字段设置为 null,然后对 facebook 执行相同操作。用户名字段设置为 mongodb 集合中的索引。每当有人通过 passport.js 登录时尝试设置用户名字段
-
感谢大家的帮助。我使用的是“电子邮件”而不是“用户名”......我更改了我的用户架构以使“电子邮件”字段成为“用户名”,并且用户是否输入电子邮件或文本,因为用户名变得无关紧要。然后,在 mongodb 中,如果用户手动注册(使用本地身份验证),则用户名将成为用户在输入字段中键入的名称。但是,如果用户选择 Google 或 Facebook 身份验证,则用户名将作为用户在相关平台(GoogleId 或 FacebookId)上的配置文件 ID 存储在 mongoDB 中。
标签: javascript node.js mongodb passport.js