Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 31 additions & 7 deletions server/config/passport.js
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,22 @@ const getVerifiedEmails = (githubEmails) =>
const getPrimaryEmail = (githubEmails) =>
(lodash.find(githubEmails, { primary: true }) || {}).value;

/**
* Get primary email from Google OAuth profile.
* Returns the first email if available, or null if emails array is missing/empty.
*/
const getGooglePrimaryEmail = (googleEmails) => {
if (
!googleEmails ||
!Array.isArray(googleEmails) ||
googleEmails.length === 0
) {
return null;
}
const primaryEmail = googleEmails[0]?.value?.trim();
return primaryEmail || null;
};

/**
* Sign in with GitHub.
*/
Expand Down Expand Up @@ -240,8 +256,18 @@ passport.use(
},
async (req, accessToken, refreshToken, profile, done) => {
try {
// Validate that emails array exists and has at least one element
const primaryEmail = getGooglePrimaryEmail(profile._json?.emails);
if (!primaryEmail) {
return done(null, false, {
msg:
'Unable to retrieve email from Google account. ' +
'Please ensure your Google account has an email address and try again.'
});
}

const existingUser = await User.findOne({
google: profile._json.emails[0].value
google: primaryEmail
}).exec();

if (existingUser) {
Expand All @@ -258,18 +284,16 @@ passport.use(
return done(null, existingUser);
}

const primaryEmail = profile._json.emails[0].value;

if (req.user) {
if (!req.user.google) {
req.user.google = profile._json.emails[0].value;
req.user.google = primaryEmail;
req.user.tokens.push({ kind: 'google', accessToken });
req.user.verified = User.EmailConfirmation().Verified;
}
await req.user.save();
return done(null, req.user);
}
let username = profile._json.emails[0].value.split('@')[0];
let username = primaryEmail.split('@')[0];
const existingEmailUser = await User.findByEmail(primaryEmail);
const existingUsernameUser = await User.findByUsername(username, {
caseInsensitive: true
Expand All @@ -285,7 +309,7 @@ passport.use(
return done(null, false, { msg: accountSuspensionMessage });
}
existingEmailUser.email = existingEmailUser.email || primaryEmail;
existingEmailUser.google = profile._json.emails[0].value;
existingEmailUser.google = primaryEmail;
existingEmailUser.username = existingEmailUser.username || username;
existingEmailUser.tokens.push({
kind: 'google',
Expand All @@ -301,7 +325,7 @@ passport.use(

const user = new User();
user.email = primaryEmail;
user.google = profile._json.emails[0].value;
user.google = primaryEmail;
user.username = username;
user.tokens.push({ kind: 'google', accessToken });
user.name = profile._json.displayName;
Expand Down