2025-08-27 12:59:40 -04:00
|
|
|
import { logger } from '@librechat/data-schemas';
|
2025-09-23 14:46:53 -04:00
|
|
|
import { ErrorTypes } from 'librechat-data-provider';
|
2025-08-27 12:59:40 -04:00
|
|
|
import type { IUser, UserMethods } from '@librechat/data-schemas';
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Finds or migrates a user for OpenID authentication
|
|
|
|
|
* @returns user object (with migration fields if needed), error message, and whether migration is needed
|
|
|
|
|
*/
|
|
|
|
|
export async function findOpenIDUser({
|
|
|
|
|
openidId,
|
|
|
|
|
findUser,
|
2025-09-23 14:46:53 -04:00
|
|
|
email,
|
|
|
|
|
idOnTheSource,
|
2025-08-27 12:59:40 -04:00
|
|
|
strategyName = 'openid',
|
|
|
|
|
}: {
|
|
|
|
|
openidId: string;
|
|
|
|
|
findUser: UserMethods['findUser'];
|
|
|
|
|
email?: string;
|
2025-09-23 14:46:53 -04:00
|
|
|
idOnTheSource?: string;
|
2025-08-27 12:59:40 -04:00
|
|
|
strategyName?: string;
|
|
|
|
|
}): Promise<{ user: IUser | null; error: string | null; migration: boolean }> {
|
2025-09-23 14:46:53 -04:00
|
|
|
const primaryConditions = [];
|
|
|
|
|
|
|
|
|
|
if (openidId && typeof openidId === 'string') {
|
|
|
|
|
primaryConditions.push({ openidId });
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (idOnTheSource && typeof idOnTheSource === 'string') {
|
|
|
|
|
primaryConditions.push({ idOnTheSource });
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
let user = null;
|
|
|
|
|
if (primaryConditions.length > 0) {
|
|
|
|
|
user = await findUser({ $or: primaryConditions });
|
|
|
|
|
}
|
2025-08-27 12:59:40 -04:00
|
|
|
if (!user && email) {
|
|
|
|
|
user = await findUser({ email });
|
|
|
|
|
logger.warn(
|
|
|
|
|
`[${strategyName}] user ${user ? 'found' : 'not found'} with email: ${email} for openidId: ${openidId}`,
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
// If user found by email, check if they're allowed to use OpenID provider
|
|
|
|
|
if (user && user.provider && user.provider !== 'openid') {
|
|
|
|
|
logger.warn(
|
|
|
|
|
`[${strategyName}] Attempted OpenID login by user ${user.email}, was registered with "${user.provider}" provider`,
|
|
|
|
|
);
|
2025-09-23 14:46:53 -04:00
|
|
|
return { user: null, error: ErrorTypes.AUTH_FAILED, migration: false };
|
2025-08-27 12:59:40 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// If user found by email but doesn't have openidId, prepare for migration
|
|
|
|
|
if (user && !user.openidId) {
|
|
|
|
|
logger.info(
|
|
|
|
|
`[${strategyName}] Preparing user ${user.email} for migration to OpenID with sub: ${openidId}`,
|
|
|
|
|
);
|
|
|
|
|
user.provider = 'openid';
|
|
|
|
|
user.openidId = openidId;
|
|
|
|
|
return { user, error: null, migration: true };
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return { user, error: null, migration: false };
|
|
|
|
|
}
|