LibreChat/api/strategies/socialLogin.js
Marco Beretta b7fef6958b
🔒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
2024-06-06 13:23:11 -04:00

38 lines
1.1 KiB
JavaScript

const { createNewUser, handleExistingUser } = require('./process');
const { logger } = require('~/config');
const { findUserByEmail } = require('~/server/services/UserService');
const { isEnabled } = require('~/server/utils');
const socialLogin =
(provider, getProfileDetails) => async (accessToken, refreshToken, profile, cb) => {
try {
const { email, id, avatarUrl, username, name, emailVerified } = getProfileDetails(profile);
const oldUser = await findUserByEmail(email);
const ALLOW_SOCIAL_REGISTRATION = isEnabled(process.env.ALLOW_SOCIAL_REGISTRATION);
if (oldUser) {
await handleExistingUser(oldUser, avatarUrl);
return cb(null, oldUser);
}
if (ALLOW_SOCIAL_REGISTRATION) {
const newUser = await createNewUser({
email,
avatarUrl,
provider,
providerKey: `${provider}Id`,
providerId: id,
username,
name,
emailVerified,
});
return cb(null, newUser);
}
} catch (err) {
logger.error(`[${provider}Login]`, err);
return cb(err);
}
};
module.exports = socialLogin;