n8n/packages/cli/src/auth/methods/ldap.ts

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

71 lines
2.1 KiB
TypeScript
Raw Normal View History

import { Container } from 'typedi';
import { InternalHooks } from '@/InternalHooks';
import { LdapService } from '@/Ldap/ldap.service';
2023-01-24 17:18:39 -08:00
import {
createLdapUserOnLocalDb,
getLdapUserRole,
getUserByEmail,
getAuthIdentityByLdapId,
isLdapEnabled,
2023-01-24 17:18:39 -08:00
mapLdapAttributesToUser,
createLdapAuthIdentity,
updateLdapUserOnLocalDb,
} from '@/Ldap/helpers';
import type { User } from '@db/entities/User';
export const handleLdapLogin = async (
loginId: string,
password: string,
): Promise<User | undefined> => {
if (!isLdapEnabled()) return undefined;
2023-01-24 17:18:39 -08:00
const ldapService = Container.get(LdapService);
2023-01-24 17:18:39 -08:00
if (!ldapService.config.loginEnabled) return undefined;
2023-01-24 17:18:39 -08:00
const { loginIdAttribute, userFilter } = ldapService.config;
2023-01-24 17:18:39 -08:00
const ldapUser = await ldapService.findAndAuthenticateLdapUser(
2023-01-24 17:18:39 -08:00
loginId,
password,
loginIdAttribute,
userFilter,
);
if (!ldapUser) return undefined;
const [ldapId, ldapAttributesValues] = mapLdapAttributesToUser(ldapUser, ldapService.config);
2023-01-24 17:18:39 -08:00
const { email: emailAttributeValue } = ldapAttributesValues;
if (!ldapId || !emailAttributeValue) return undefined;
const ldapAuthIdentity = await getAuthIdentityByLdapId(ldapId);
if (!ldapAuthIdentity) {
const emailUser = await getUserByEmail(emailAttributeValue);
// check if there is an email user with the same email as the authenticated LDAP user trying to log-in
if (emailUser && emailUser.email === emailAttributeValue) {
const identity = await createLdapAuthIdentity(emailUser, ldapId);
await updateLdapUserOnLocalDb(identity, ldapAttributesValues);
} else {
const role = await getLdapUserRole();
const user = await createLdapUserOnLocalDb(role, ldapAttributesValues, ldapId);
void Container.get(InternalHooks).onUserSignup(user, {
2023-01-24 17:18:39 -08:00
user_type: 'ldap',
was_disabled_ldap_user: false,
});
return user;
}
} else {
if (ldapAuthIdentity.user) {
if (ldapAuthIdentity.user.disabled) return undefined;
await updateLdapUserOnLocalDb(ldapAuthIdentity, ldapAttributesValues);
}
}
// Retrieve the user again as user's data might have been updated
return (await getAuthIdentityByLdapId(ldapId))?.user;
};