🔒refactor: social login and remove direct user model access in strategies (#2946)

* refactor: checking `ALLOW_SOCIAL_REGISTRATION` with `isEnabled`

* feat: Add findUserByEmail function to UserService

This commit adds a new function, , to the  module. This function retrieves a user document from the database based on the provided email. It returns the user document if found, otherwise it returns null. If there is a problem during user retrieval, an error is thrown.

* refactor: add socialLogin to remove repetitive code
This commit is contained in:
Marco Beretta 2024-06-06 19:23:11 +02:00 committed by GitHub
parent 5452d4c20c
commit b7fef6958b
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
6 changed files with 104 additions and 143 deletions

View file

@ -1,40 +1,16 @@
const { Strategy: GoogleStrategy } = require('passport-google-oauth20');
const { createNewUser, handleExistingUser } = require('./process');
const { logger } = require('~/config');
const User = require('~/models/User');
const socialLogin = require('./socialLogin');
const googleLogin = async (accessToken, refreshToken, profile, cb) => {
try {
const email = profile.emails[0].value;
const googleId = profile.id;
const oldUser = await User.findOne({ email });
const ALLOW_SOCIAL_REGISTRATION =
process.env.ALLOW_SOCIAL_REGISTRATION?.toLowerCase() === 'true';
const avatarUrl = profile.photos[0].value;
const getProfileDetails = (profile) => ({
email: profile.emails[0].value,
id: profile.id,
avatarUrl: profile.photos[0].value,
username: profile.name.givenName,
name: `${profile.name.givenName} ${profile.name.familyName}`,
emailVerified: profile.emails[0].verified,
});
if (oldUser) {
await handleExistingUser(oldUser, avatarUrl);
return cb(null, oldUser);
}
if (ALLOW_SOCIAL_REGISTRATION) {
const newUser = await createNewUser({
email,
avatarUrl,
provider: 'google',
providerKey: 'googleId',
providerId: googleId,
username: profile.name.givenName,
name: `${profile.name.givenName} ${profile.name.familyName}`,
emailVerified: profile.emails[0].verified,
});
return cb(null, newUser);
}
} catch (err) {
logger.error('[googleLogin]', err);
return cb(err);
}
};
const googleLogin = socialLogin('google', getProfileDetails);
module.exports = () =>
new GoogleStrategy(