CustomCredentials.php 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Security\Http\Authenticator\Passport\Credentials;
  11. use Symfony\Component\Security\Core\Exception\BadCredentialsException;
  12. use Symfony\Component\Security\Core\User\UserInterface;
  13. /**
  14. * Implements credentials checking using a custom checker function.
  15. *
  16. * @author Wouter de Jong <wouter@wouterj.nl>
  17. *
  18. * @final
  19. * @experimental in 5.2
  20. */
  21. class CustomCredentials implements CredentialsInterface
  22. {
  23. private $customCredentialsChecker;
  24. private $credentials;
  25. private $resolved = false;
  26. /**
  27. * @param callable $customCredentialsChecker the check function. If this function does not return `true`, a
  28. * BadCredentialsException is thrown. You may also throw a more
  29. * specific exception in the function.
  30. * @param $credentials
  31. */
  32. public function __construct(callable $customCredentialsChecker, $credentials)
  33. {
  34. $this->customCredentialsChecker = $customCredentialsChecker;
  35. $this->credentials = $credentials;
  36. }
  37. public function executeCustomChecker(UserInterface $user): void
  38. {
  39. $checker = $this->customCredentialsChecker;
  40. if (true !== $checker($this->credentials, $user)) {
  41. throw new BadCredentialsException('Credentials check failed as the callable passed to CustomCredentials did not return "true".');
  42. }
  43. $this->resolved = true;
  44. }
  45. public function isResolved(): bool
  46. {
  47. return $this->resolved;
  48. }
  49. }