diff --git a/src/User/Framework/Security/LdapUserProvider.php b/src/User/Framework/Security/LdapUserProvider.php index ce435fa..6218939 100644 --- a/src/User/Framework/Security/LdapUserProvider.php +++ b/src/User/Framework/Security/LdapUserProvider.php @@ -156,7 +156,7 @@ class LdapUserProvider implements UserProviderInterface, PasswordUpgraderInterfa $extraFields[$field] = $this->getAttributeValue($entry, $field); } - $dbUser = $this->getDbUser($identifier); + $dbUser = $this->getDbUser($identifier, $entry); if (null === $dbUser) { $dbUser = new User(); @@ -164,23 +164,32 @@ class LdapUserProvider implements UserProviderInterface, PasswordUpgraderInterfa } $dbUser - ->setName($entry->getAttribute($this->displayNameAttribute)[0] ?? null) - ->setEmail($entry->getAttribute($this->emailAttribute)[0] ?? null) - ->setUsername($entry->getAttribute($this->usernameAttribute)[0] ?? null); - + ->setName( $this->getAttributeValue($entry, $this->displayNameAttribute)[0] ?? null) + ->setEmail($this->getAttributeValue($entry, $this->emailAttribute)[0] ?? null) + ->setUsername($this->getAttributeValue($entry, $this->usernameAttribute) ?? null); + $this->userRepository->getEntityManager()->persist($dbUser); $this->userRepository->getEntityManager()->flush(); return $dbUser; } - private function getDbUser(string $identifier): ?UserInterface + private function getDbUser(string $identifier, Entry $entry): ?UserInterface { if (in_array($this->uidKey, ['mail', 'email'])) { - return $this->userRepository->findOneBy(['email' => $identifier]); + $dbUser = $this->userRepository->findOneBy(['email' => $identifier]); } else { - return $this->userRepository->findOneBy(['username' => $identifier]); + $dbUser = $this->userRepository->findOneBy(['username' => $identifier]); } + + // Attempt to map LDAP user to existing user + if (null === $dbUser) { + if ($entry->hasAttribute($this->emailAttribute)) { + $dbUser = $this->userRepository->findOneBy(['email' => $this->getAttributeValue($entry, $this->emailAttribute)]);; + } + } + + return $dbUser; } private function getAttributeValue(Entry $entry, string $attribute): mixed