如何通过多个OAuth2提供者login时减less代码重复?

我正在使用Node.jsExpressPassportMongoose节点模块。

用户点击sign in with provider入时有两种情况。 这是一个GitHub策略的例子:

1.如果用户已经login,请将此github帐户链接到当前login的用户。

2.如果用户没有login,请检查是否是首次使用Githublogin,或者是否是返回用户。

问:我可以使用MongoDB查询生成器或其他技术以某种方式合并这些代码吗?

 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. 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); }); }); } 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(); user.github = profile.id; user.tokens.push({ kind: 'github', accessToken: accessToken }); user.profile.name = profile.displayName; user.profile.email = profile._json.email; user.profile.picture = profile._json.avatar_url; user.profile.location = profile._json.location; user.profile.website = profile._json.blog; user.save(function(err) { done(err, user); }); }); } 

不知道你在问什么,但在这里,你可以把类似的部分变成这样的函数:

 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更新命令,而不是获取和保存整个文档。