| 1 |
<?php |
| 2 |
|
| 3 |
declare(strict_types=1); |
| 4 |
|
| 5 |
namespace Org_Heigl\AuthLdap; |
| 6 |
|
| 7 |
use Exception; |
| 8 |
use Org_Heigl\AuthLdap\Value\LoggedInUser; |
| 9 |
use Org_Heigl\AuthLdap\Value\Password; |
| 10 |
use Org_Heigl\AuthLdap\Value\UserFilter; |
| 11 |
use Org_Heigl\AuthLdap\Value\Username; |
| 12 |
use WP_Error; |
| 13 |
use WP_User; |
| 14 |
|
| 15 |
final class Authenticate |
| 16 |
{ |
| 17 |
private UserFilter $filter; |
| 18 |
|
| 19 |
private LdapList $backend; |
| 20 |
private LoggerInterface $logger; |
| 21 |
public function __construct(UserFilter $filter, LdapList $backend, LoggerInterface $logger) |
| 22 |
{ |
| 23 |
$this->filter = $filter; |
| 24 |
$this->backend = $backend; |
| 25 |
$this->logger = $logger; |
| 26 |
} |
| 27 |
|
| 28 |
/** |
| 29 |
* @param null|WP_User|WP_Error |
| 30 |
* @param string $username |
| 31 |
* @param string $password |
| 32 |
* @return WP_User|WP_Error|LoggedInUser|false |
| 33 |
*/ |
| 34 |
public function __invoke( |
| 35 |
$user, |
| 36 |
$username, |
| 37 |
#[\SensitiveParameter] |
| 38 |
$password |
| 39 |
) { |
| 40 |
// If the user has already been authenticated (only in that case we get a |
| 41 |
// WP_User-Object as $user) we skip LDAP-authentication and simply return |
| 42 |
// the existing user-object |
| 43 |
if ($user instanceof WP_User) { |
| 44 |
$this->logger->log(sprintf( |
| 45 |
'User %s has already been authenticated - skipping LDAP-Authentication', |
| 46 |
$user->get('nickname') |
| 47 |
)); |
| 48 |
return $user; |
| 49 |
} |
| 50 |
|
| 51 |
$this->logger->log(sprintf( |
| 52 |
'User "%s" logging in', |
| 53 |
$username |
| 54 |
)); |
| 55 |
|
| 56 |
try { |
| 57 |
$username = Username::fromMixed($username); |
| 58 |
} catch (\InvalidArgumentException $e) { |
| 59 |
$this->logger->log($e->getMessage()); |
| 60 |
|
| 61 |
return false; |
| 62 |
} |
| 63 |
|
| 64 |
try { |
| 65 |
$password = Password::fromMixed($password); |
| 66 |
} catch (\InvalidArgumentException $e) { |
| 67 |
$this->logger->log($e->getMessage()); |
| 68 |
return false; |
| 69 |
} |
| 70 |
|
| 71 |
try { |
| 72 |
$this->logger->log('about to do LDAP authentication'); |
| 73 |
if ($this->backend->Authenticate((string) $username, (string) $password, (string) $this->filter)) { |
| 74 |
$this->logger->log('LDAP authentication successful'); |
| 75 |
return LoggedInUser::fromUsernameAndPassword($username, $password); |
| 76 |
} |
| 77 |
} catch (Exception $e) { |
| 78 |
$this->logger->log(sprintf( |
| 79 |
'LDAP authentication failed with exception: %s', |
| 80 |
$e->getMessage() |
| 81 |
)); |
| 82 |
return false; |
| 83 |
} |
| 84 |
|
| 85 |
$this->logger->log('LDAP authentication failed'); |
| 86 |
return false; |
| 87 |
} |
| 88 |
} |
| 89 |
|