Javascript 如何在通过多个OAuth2提供程序登录时减少代码重复?
我正在使用Node.js、Express、Passport、Mongoose节点模块 当用户单击“使用提供商登录”时,有两种情况。下面是GitHub战略的一个示例: 一,。如果用户已登录,请将此github帐户链接到当前登录的用户 二,。如果用户未登录,则检查这是第一次使用Github登录还是返回用户 问:我是否可以使用MongoDB查询生成器或其他技术整合此代码?Javascript 如何在通过多个OAuth2提供程序登录时减少代码重复?,javascript,node.js,express,mongoose,passport.js,Javascript,Node.js,Express,Mongoose,Passport.js,我正在使用Node.js、Express、Passport、Mongoose节点模块 当用户单击“使用提供商登录”时,有两种情况。下面是GitHub战略的一个示例: 一,。如果用户已登录,请将此github帐户链接到当前登录的用户 二,。如果用户未登录,则检查这是第一次使用Github登录还是返回用户 问:我是否可以使用MongoDB查询生成器或其他技术整合此代码? 不确定您要问什么,但在这里,您可以将类似的部分放入如下函数中: if (req.user) { // Already logg
不确定您要问什么,但在这里,您可以将类似的部分放入如下函数中:
if (req.user) {
// Already logged in. Clicked on "Link Github account" on Settings page.
User.findById(req.user.id, function(err, user) {
// Merge Github with local account for the current user.
updateUserGithub(user, profile, done);
});
} else {
// Unauthenticated user arriving from Login/Signup page.
User.findOne({ github: profile.id }, function(err, existingUser) {
// Returning user. Stop here.
if (existingUser) return done(null, existingUser);
// First time. Create a new user.
var user = new User();
updateUserGithub(user, profile, done);
});
}
function updateUserGithub(user, profile, done) {
user.github = profile.id;
user.tokens.push({ kind: 'github', accessToken: accessToken });
user.profile.name = profile.displayName;
user.profile.email = user.profile.email || profile._json.email;
user.profile.picture = user.profile.picture || profile._json.avatar_url;
user.profile.location = user.profile.location || profile._json.location;
user.profile.website = user.profile.website || profile._json.blog;
user.save(function(err) {
done(err, user);
});
}
如果此处没有默认值逻辑(如user.profile.website | | | profile._json.blog;
),则可以使用mongodb update命令,而不是获取和保存整个文档
if (req.user) {
// Already logged in. Clicked on "Link Github account" on Settings page.
User.findById(req.user.id, function(err, user) {
// Merge Github with local account for the current user.
updateUserGithub(user, profile, done);
});
} else {
// Unauthenticated user arriving from Login/Signup page.
User.findOne({ github: profile.id }, function(err, existingUser) {
// Returning user. Stop here.
if (existingUser) return done(null, existingUser);
// First time. Create a new user.
var user = new User();
updateUserGithub(user, profile, done);
});
}
function updateUserGithub(user, profile, done) {
user.github = profile.id;
user.tokens.push({ kind: 'github', accessToken: accessToken });
user.profile.name = profile.displayName;
user.profile.email = user.profile.email || profile._json.email;
user.profile.picture = user.profile.picture || profile._json.avatar_url;
user.profile.location = user.profile.location || profile._json.location;
user.profile.website = user.profile.website || profile._json.blog;
user.save(function(err) {
done(err, user);
});
}