From 5aacd981b4a30bb81f470a39379835fe67811a05 Mon Sep 17 00:00:00 2001 From: rudy Date: Mon, 19 Jun 2023 14:22:05 +0200 Subject: [PATCH 1/4] issue-19: ajout de logs des exceptions PDOExceptions --- src/Service/SQLLoginService.php | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/src/Service/SQLLoginService.php b/src/Service/SQLLoginService.php index 16b3d45..2e1d549 100644 --- a/src/Service/SQLLoginService.php +++ b/src/Service/SQLLoginService.php @@ -6,18 +6,20 @@ use App\SQLLogin\SQLLoginConnect; use App\SQLLogin\SQLLoginRequest; use PDO; use PDOException; +use Psr\Log\LoggerInterface; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; class SQLLoginService extends AbstractController { public SQLLoginRequest $sqlLoginRequest; - public function __construct(SQLLoginRequest $sqlLoginRequest) + public function __construct(SQLLoginRequest $sqlLoginRequest, private LoggerInterface $loggerInterface) { $this->sqlLoginRequest = $sqlLoginRequest; + $this->loggerInterface = $loggerInterface; } - public function fetchDatas(string $login) + public function fetchDatas(string $login): array { try { $dbh = $this->getConnection(); @@ -29,7 +31,7 @@ class SQLLoginService extends AbstractController $datas = $query->fetch(PDO::FETCH_ASSOC); } catch (PDOException $e) { \Sentry\captureException($e); - + $this->loggerInterface->critical($e->getMessage()); throw new PDOException(); } @@ -45,7 +47,7 @@ class SQLLoginService extends AbstractController $query->execute([$this->sqlLoginRequest->getLoginColumnName() => $login]); $password = $query->fetch(PDO::FETCH_ASSOC); } catch (PDOException $e) { - \Sentry\captureException($e); + $this->loggerInterface->critical($e->getMessage()); throw new PDOException(); } if ($password) { @@ -58,7 +60,7 @@ class SQLLoginService extends AbstractController return false; } - public function getConnection() + public function getConnection(): PDO { // Appel du singleton $sqlLogin = SQLLoginConnect::getInstance(); -- 2.17.1 From 3e4511968457e7de7af1e45be98f361ad16334e8 Mon Sep 17 00:00:00 2001 From: rudy Date: Mon, 19 Jun 2023 15:56:55 +0200 Subject: [PATCH 2/4] =?UTF-8?q?issue-19:=20s=C3=A9paration=20des=20excepti?= =?UTF-8?q?ons=20pour=20=C3=A9viter=20les=20erreurs=20g=C3=A9n=C3=A9riques?= =?UTF-8?q?,=20message=20personalis=C3=A9=20par=20type=20d'erreur?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Controller/SecurityController.php | 18 ++++++++++-- ... => DataToFetchConfigurationException.php} | 2 +- .../Exception/DatabaseConnectionException.php | 9 ++++++ .../LoginElementsConfigurationException.php | 9 ++++++ ...ption.php => NullDataToFetchException.php} | 2 +- .../NullPasswordColumnNameException.php | 9 ++++++ .../SecurityPatternConfigurationException.php | 9 ++++++ src/SQLLogin/SQLLoginRequest.php | 18 ++++++++---- src/Security/Hasher/PasswordEncoder.php | 8 +++-- src/Security/SQLLoginUserAuthenticator.php | 29 +++++++++++++++---- src/Service/SQLLoginService.php | 29 ++++++++++++++++--- translations/messages.en.xlf | 12 ++++++++ translations/messages.fr.xlf | 14 ++++++++- 13 files changed, 143 insertions(+), 25 deletions(-) rename src/SQLLogin/Exception/{InvalidSQLLoginConfigurationException.php => DataToFetchConfigurationException.php} (50%) create mode 100644 src/SQLLogin/Exception/DatabaseConnectionException.php create mode 100644 src/SQLLogin/Exception/LoginElementsConfigurationException.php rename src/SQLLogin/Exception/{InvalidSQLLoginException.php => NullDataToFetchException.php} (55%) create mode 100644 src/SQLLogin/Exception/NullPasswordColumnNameException.php create mode 100644 src/SQLLogin/Exception/SecurityPatternConfigurationException.php diff --git a/src/Controller/SecurityController.php b/src/Controller/SecurityController.php index 08a0c76..cb525c5 100644 --- a/src/Controller/SecurityController.php +++ b/src/Controller/SecurityController.php @@ -36,9 +36,21 @@ class SecurityController extends AbstractController $loginForm->get('password')->addError(new FormError($trans->trans('error.password', [], 'messages'))); $request->getSession()->remove(SQLLoginUserAuthenticator::ERROR_PASSWORD); } - if ($request->getSession()->has(SQLLoginUserAuthenticator::ERROR_SQL_LOGIN)) { - $loginForm->addError(new FormError($trans->trans('error.sql_login', [], 'messages'))); - $request->getSession()->remove(SQLLoginUserAuthenticator::ERROR_SQL_LOGIN); + if ($request->getSession()->has(SQLLoginUserAuthenticator::ERROR_PDO)) { + $loginForm->addError(new FormError($trans->trans('error.pdo', [], 'messages'))); + $request->getSession()->remove(SQLLoginUserAuthenticator::ERROR_PDO); + } + if ($request->getSession()->has(SQLLoginUserAuthenticator::ERROR_CONFIGURATION)) { + $loginForm->addError(new FormError($trans->trans('error.configuration', [], 'messages'))); + $request->getSession()->remove(SQLLoginUserAuthenticator::ERROR_CONFIGURATION); + } + if ($request->getSession()->has(SQLLoginUserAuthenticator::ERROR_DATA_TO_FETCH_CONFIGURATION)) { + $loginForm->addError(new FormError($trans->trans('error.data_to_fetch_configuration', [], 'messages'))); + $request->getSession()->remove(SQLLoginUserAuthenticator::ERROR_DATA_TO_FETCH_CONFIGURATION); + } + if ($request->getSession()->has(SQLLoginUserAuthenticator::ERROR_SECURITY_PATTERN_CONFIGURATION)) { + $loginForm->addError(new FormError($trans->trans('error.security_pattern_configuration', [], 'messages'))); + $request->getSession()->remove(SQLLoginUserAuthenticator::ERROR_SECURITY_PATTERN_CONFIGURATION); } } diff --git a/src/SQLLogin/Exception/InvalidSQLLoginConfigurationException.php b/src/SQLLogin/Exception/DataToFetchConfigurationException.php similarity index 50% rename from src/SQLLogin/Exception/InvalidSQLLoginConfigurationException.php rename to src/SQLLogin/Exception/DataToFetchConfigurationException.php index 156abf7..7b09626 100644 --- a/src/SQLLogin/Exception/InvalidSQLLoginConfigurationException.php +++ b/src/SQLLogin/Exception/DataToFetchConfigurationException.php @@ -4,6 +4,6 @@ namespace App\SQLLogin\Exception; use Exception; -class InvalidSQLLoginConfigurationException extends Exception +class DataToFetchConfigurationException extends Exception { } diff --git a/src/SQLLogin/Exception/DatabaseConnectionException.php b/src/SQLLogin/Exception/DatabaseConnectionException.php new file mode 100644 index 0000000..770ea6b --- /dev/null +++ b/src/SQLLogin/Exception/DatabaseConnectionException.php @@ -0,0 +1,9 @@ +config[self::DATA_TO_FETCH] as $data) { - $scope .= $data.','; - } - $scope = substr($scope, 0, -1); + if ($this->config[self::DATA_TO_FETCH]) { + foreach ($this->config[self::DATA_TO_FETCH] as $data) { + $scope .= $data.','; + } + // On enlève la dernière virgule + $scope = substr($scope, 0, -1); - return 'SELECT '.$scope.' FROM '.$this->getTableName().' WHERE '.$this->getLoginColumnName().' = :'.$this->getLoginColumnName().';'; + return 'SELECT '.$scope.' FROM '.$this->getTableName().' WHERE '.$this->getLoginColumnName().' = :'.$this->getLoginColumnName().';'; + } + throw new NullDataToFetchException(); } /** * Construction de la string pour la requête préparée selon la configuration yaml * intègre la récupération du mot de passe hashé, du salt et de besoin d'upgrade de la méthode de hashage */ - public function getRequestPassword() + public function getRequestPassword(): string { $fields = $this->getPasswordColumnName(); if (!empty($this->getSaltColumnName())) { diff --git a/src/Security/Hasher/PasswordEncoder.php b/src/Security/Hasher/PasswordEncoder.php index c2d725a..91ffa7b 100644 --- a/src/Security/Hasher/PasswordEncoder.php +++ b/src/Security/Hasher/PasswordEncoder.php @@ -2,8 +2,9 @@ namespace App\Security\Hasher; -use App\SQLLogin\Exception\InvalidSQLLoginConfigurationException; use App\SQLLogin\Exception\InvalidSQLPasswordException; +use App\SQLLogin\Exception\SecurityPatternConfigurationException; +use Psr\Log\LoggerInterface; use Symfony\Component\PasswordHasher\Exception\InvalidPasswordException; use Symfony\Component\PasswordHasher\Hasher\CheckPasswordLengthTrait; use Symfony\Component\PasswordHasher\LegacyPasswordHasherInterface; @@ -19,7 +20,7 @@ class PasswordEncoder implements LegacyPasswordHasherInterface protected array $hashAlgoLegacy; protected array $securityPattern; - public function __construct(?string $pepper, string $hashAlgoLegacy, string $securityPattern) + public function __construct(?string $pepper, string $hashAlgoLegacy, string $securityPattern, private LoggerInterface $loggerInterface) { $this->pepper = $pepper; $this->hashAlgoLegacy = explode(',', $hashAlgoLegacy); @@ -88,7 +89,8 @@ class PasswordEncoder implements LegacyPasswordHasherInterface foreach ($this->securityPattern as $term) { if (self::PEPPER_PATTERN !== $term && self::PASSWORD_PATTERN !== $term && self::SALT_PATTERN !== $term) { - throw new InvalidSQLLoginConfigurationException(); + $this->loggerInterface->critical('La configuration du security pattern est invalide, les termes autorisés sont : '.self::PASSWORD_PATTERN.', '.self::SALT_PATTERN.' et '.self::PEPPER_PATTERN); + throw new SecurityPatternConfigurationException(); } } $completedPlainPassword = ''; diff --git a/src/Security/SQLLoginUserAuthenticator.php b/src/Security/SQLLoginUserAuthenticator.php index 1d3394e..842ad16 100644 --- a/src/Security/SQLLoginUserAuthenticator.php +++ b/src/Security/SQLLoginUserAuthenticator.php @@ -5,8 +5,11 @@ namespace App\Security; use App\Entity\User; use App\Security\Hasher\PasswordEncoder; use App\Service\SQLLoginService; +use App\SQLLogin\Exception\DatabaseConnectionException; +use App\SQLLogin\Exception\DataToFetchConfigurationException; use App\SQLLogin\Exception\InvalidSQLPasswordException; -use PDOException; +use App\SQLLogin\Exception\LoginElementsConfigurationException; +use App\SQLLogin\Exception\SecurityPatternConfigurationException; use Symfony\Component\HttpFoundation\RedirectResponse; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; @@ -24,7 +27,11 @@ class SQLLoginUserAuthenticator extends AbstractLoginFormAuthenticator public const LOGIN_ROUTE = 'app_login'; public const ERROR_LOGIN = 'error_login'; public const ERROR_PASSWORD = 'error_password'; + public const ERROR_PDO = 'error_pdo'; public const ERROR_SQL_LOGIN = 'error_sql_login'; + public const ERROR_CONFIGURATION = 'error_configuration'; + public const ERROR_DATA_TO_FETCH_CONFIGURATION = 'error_data_to_fetch_configuration'; + public const ERROR_SECURITY_PATTERN_CONFIGURATION = 'error_security_pattern_configuration'; protected string $baseUrl; private SQLLoginService $sqlLoginService; @@ -65,11 +72,15 @@ class SQLLoginUserAuthenticator extends AbstractLoginFormAuthenticator $login = $form['login']; $plaintextPassword = $form['password']; $rememberMe = isset($form['_remember_me']) ? true : false; + $session = $request->getSession(); try { // requête préparée list($remoteHashedPassword, $remoteSalt) = $this->sqlLoginService->fetchPassword($login); - } catch (PDOException $e) { - $request->getSession()->set(self::ERROR_SQL_LOGIN, true); + } catch (DatabaseConnectionException $e) { + $session->set(self::ERROR_PDO, true); + throw new AuthenticationException(); + } catch (LoginElementsConfigurationException $e) { + $session->set(self::ERROR_CONFIGURATION, true); throw new AuthenticationException(); } if ($remoteHashedPassword) { @@ -90,10 +101,16 @@ class SQLLoginUserAuthenticator extends AbstractLoginFormAuthenticator return $passport; } catch (InvalidSQLPasswordException $e) { - $request->getSession()->set(self::ERROR_PASSWORD, true); + $session->set(self::ERROR_PASSWORD, true); throw new AuthenticationException(); - } catch (PDOException $e) { - $request->getSession()->set(self::ERROR_SQL_LOGIN, true); + } catch (DataToFetchConfigurationException $e) { + $session->set(self::ERROR_DATA_TO_FETCH_CONFIGURATION, true); + throw new AuthenticationException(); + } catch (DatabaseConnectionException $e) { + $session->set(self::ERROR_PDO, true); + throw new AuthenticationException(); + } catch (SecurityPatternConfigurationException $e) { + $session->set(self::ERROR_SECURITY_PATTERN_CONFIGURATION, true); throw new AuthenticationException(); } } diff --git a/src/Service/SQLLoginService.php b/src/Service/SQLLoginService.php index 2e1d549..6b90546 100644 --- a/src/Service/SQLLoginService.php +++ b/src/Service/SQLLoginService.php @@ -2,6 +2,10 @@ namespace App\Service; +use App\SQLLogin\Exception\DatabaseConnectionException; +use App\SQLLogin\Exception\DataToFetchConfigurationException; +use App\SQLLogin\Exception\LoginElementsConfigurationException; +use App\SQLLogin\Exception\NullDataToFetchException; use App\SQLLogin\SQLLoginConnect; use App\SQLLogin\SQLLoginRequest; use PDO; @@ -23,16 +27,25 @@ class SQLLoginService extends AbstractController { try { $dbh = $this->getConnection(); + } catch (PDOException $e) { + $this->loggerInterface->critical($e->getMessage()); + throw new DatabaseConnectionException($e->getMessage()); + } + try { // forge de la requête $request = $this->sqlLoginRequest->getRequestScope(); + } catch (NullDataToFetchException $e) { + throw new DataToFetchConfigurationException($e->getMessage()); + } + + try { // Préparation de la requête $query = $dbh->prepare($request); $query->execute([$this->sqlLoginRequest->getLoginColumnName() => $login]); $datas = $query->fetch(PDO::FETCH_ASSOC); } catch (PDOException $e) { - \Sentry\captureException($e); $this->loggerInterface->critical($e->getMessage()); - throw new PDOException(); + throw new DataToFetchConfigurationException($e->getMessage()); } return $datas; @@ -42,13 +55,21 @@ class SQLLoginService extends AbstractController { try { $dbh = $this->getConnection(); - $request = $this->sqlLoginRequest->getRequestPassword(); + } catch (PDOException $e) { + $this->loggerInterface->critical($e->getMessage()); + throw new DatabaseConnectionException($e->getMessage()); + } + + // forge de la requête + $request = $this->sqlLoginRequest->getRequestPassword(); + + try { $query = $dbh->prepare($request); $query->execute([$this->sqlLoginRequest->getLoginColumnName() => $login]); $password = $query->fetch(PDO::FETCH_ASSOC); } catch (PDOException $e) { $this->loggerInterface->critical($e->getMessage()); - throw new PDOException(); + throw new LoginElementsConfigurationException($e->getMessage()); } if ($password) { return [ diff --git a/translations/messages.en.xlf b/translations/messages.en.xlf index f04251d..6df1993 100644 --- a/translations/messages.en.xlf +++ b/translations/messages.en.xlf @@ -21,6 +21,18 @@ error.pdo Connection to database encountered a problem + + error.configuration + Identification data references do not exist in the database + + + error.data_to_fetch_configuration + Data references to be transmitted do not exist + + + error.security_pattern_configuration + The security pattern is not allowed + diff --git a/translations/messages.fr.xlf b/translations/messages.fr.xlf index b3caf24..662608c 100644 --- a/translations/messages.fr.xlf +++ b/translations/messages.fr.xlf @@ -19,7 +19,19 @@ error.pdo - La connexion à la base de déonnées à rencontré un problème + La connexion à la base de données a rencontré un problème + + + error.configuration + Les références de données d'identification n'existent pas dans la base de données + + + error.data_to_fetch_configuration + Les références de données à transmettre n'existent pas + + + error.security_pattern_configuration + Le patron de sécurité n'est pas autorisé -- 2.17.1 From 0791727694d282cf97dbe5c27ab1c390b3102a73 Mon Sep 17 00:00:00 2001 From: rudy Date: Mon, 29 Apr 2024 10:44:38 +0200 Subject: [PATCH 3/4] feat (gestion exceptions) #19: traitement retour: typage, un seul message pour erreur login ou mdp --- src/Controller/SecurityController.php | 4 ++-- src/SQLLogin/SQLLoginRequest.php | 23 +++++++++++----------- src/Security/SQLLoginUserAuthenticator.php | 14 ++++++------- src/Service/SQLLoginService.php | 2 +- translations/messages.en.xlf | 6 +----- translations/messages.fr.xlf | 6 +----- 6 files changed, 23 insertions(+), 32 deletions(-) diff --git a/src/Controller/SecurityController.php b/src/Controller/SecurityController.php index cb525c5..6e4b75b 100644 --- a/src/Controller/SecurityController.php +++ b/src/Controller/SecurityController.php @@ -29,11 +29,11 @@ class SecurityController extends AbstractController $error = $authenticationUtils->getLastAuthenticationError(); if ($error) { if ($request->getSession()->has(SQLLoginUserAuthenticator::ERROR_LOGIN)) { - $loginForm->get('login')->addError(new FormError($trans->trans('error.login', [], 'messages'))); + $loginForm->addError(new FormError($trans->trans('error.login', [], 'messages'))); $request->getSession()->remove(SQLLoginUserAuthenticator::ERROR_LOGIN); } if ($request->getSession()->has(SQLLoginUserAuthenticator::ERROR_PASSWORD)) { - $loginForm->get('password')->addError(new FormError($trans->trans('error.password', [], 'messages'))); + $loginForm->addError(new FormError($trans->trans('error.login', [], 'messages'))); $request->getSession()->remove(SQLLoginUserAuthenticator::ERROR_PASSWORD); } if ($request->getSession()->has(SQLLoginUserAuthenticator::ERROR_PDO)) { diff --git a/src/SQLLogin/SQLLoginRequest.php b/src/SQLLogin/SQLLoginRequest.php index 80e8c9a..a71986f 100644 --- a/src/SQLLogin/SQLLoginRequest.php +++ b/src/SQLLogin/SQLLoginRequest.php @@ -69,16 +69,17 @@ class SQLLoginRequest public function getRequestScope() { $scope = ''; - if ($this->config[self::DATA_TO_FETCH]) { - foreach ($this->config[self::DATA_TO_FETCH] as $data) { - $scope .= $data.','; - } - // On enlève la dernière virgule - $scope = substr($scope, 0, -1); - - return 'SELECT '.$scope.' FROM '.$this->getTableName().' WHERE '.$this->getLoginColumnName().' = :'.$this->getLoginColumnName().';'; + if (!$this->config[self::DATA_TO_FETCH]) { + throw new NullDataToFetchException(); } - throw new NullDataToFetchException(); + + foreach ($this->config[self::DATA_TO_FETCH] as $data) { + $scope .= $data . ','; + } + // On enlève la dernière virgule + $scope = substr($scope, 0, -1); + + return 'SELECT ' . $scope . ' FROM ' . $this->getTableName() . ' WHERE ' . $this->getLoginColumnName() . ' = :' . $this->getLoginColumnName() . ';'; } /** @@ -89,9 +90,9 @@ class SQLLoginRequest { $fields = $this->getPasswordColumnName(); if (!empty($this->getSaltColumnName())) { - $fields .= ', '.$this->getSaltColumnName(); + $fields .= ', ' . $this->getSaltColumnName(); } - return 'SELECT '.$fields.' FROM '.$this->getTableName().' WHERE '.$this->getLoginColumnName().' = :'.$this->getLoginColumnName().';'; + return 'SELECT ' . $fields . ' FROM ' . $this->getTableName() . ' WHERE ' . $this->getLoginColumnName() . ' = :' . $this->getLoginColumnName() . ';'; } } diff --git a/src/Security/SQLLoginUserAuthenticator.php b/src/Security/SQLLoginUserAuthenticator.php index 842ad16..5db74cc 100644 --- a/src/Security/SQLLoginUserAuthenticator.php +++ b/src/Security/SQLLoginUserAuthenticator.php @@ -12,14 +12,12 @@ use App\SQLLogin\Exception\LoginElementsConfigurationException; use App\SQLLogin\Exception\SecurityPatternConfigurationException; use Symfony\Component\HttpFoundation\RedirectResponse; use Symfony\Component\HttpFoundation\Request; -use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; use Symfony\Component\Security\Core\Exception\AuthenticationException; use Symfony\Component\Security\Core\Security; use Symfony\Component\Security\Http\Authenticator\AbstractLoginFormAuthenticator; use Symfony\Component\Security\Http\Authenticator\Passport\Badge\RememberMeBadge; use Symfony\Component\Security\Http\Authenticator\Passport\Badge\UserBadge; -use Symfony\Component\Security\Http\Authenticator\Passport\Passport; use Symfony\Component\Security\Http\Authenticator\Passport\SelfValidatingPassport; class SQLLoginUserAuthenticator extends AbstractLoginFormAuthenticator @@ -54,19 +52,19 @@ class SQLLoginUserAuthenticator extends AbstractLoginFormAuthenticator return self::LOGIN_ROUTE === $request->attributes->get('_route') && $request->isMethod('POST'); } - public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey): ?Response + public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey): RedirectResponse { - return new RedirectResponse($this->baseUrl.'/connect/login-accept'); + return new RedirectResponse($this->baseUrl . '/connect/login-accept'); } - public function onAuthenticationFailure(Request $request, AuthenticationException $exception): Response + public function onAuthenticationFailure(Request $request, AuthenticationException $exception): RedirectResponse { $request->getSession()->set(Security::AUTHENTICATION_ERROR, $exception); - return new RedirectResponse($this->baseUrl.'/login'); + return new RedirectResponse($this->baseUrl . '/login'); } - public function authenticate(Request $request): Passport + public function authenticate(Request $request): SelfValidatingPassport { $form = $request->request->get('login'); $login = $form['login']; @@ -120,6 +118,6 @@ class SQLLoginUserAuthenticator extends AbstractLoginFormAuthenticator protected function getLoginUrl(Request $request): string { - return $this->baseUrl.'/login'; + return $this->baseUrl . '/login'; } } diff --git a/src/Service/SQLLoginService.php b/src/Service/SQLLoginService.php index 6b90546..ece37cb 100644 --- a/src/Service/SQLLoginService.php +++ b/src/Service/SQLLoginService.php @@ -51,7 +51,7 @@ class SQLLoginService extends AbstractController return $datas; } - public function fetchPassword(string $login) + public function fetchPassword($login): array|bool { try { $dbh = $this->getConnection(); diff --git a/translations/messages.en.xlf b/translations/messages.en.xlf index 6df1993..8617499 100644 --- a/translations/messages.en.xlf +++ b/translations/messages.en.xlf @@ -7,11 +7,7 @@ error.login - Incorrect login - - - error.password - Incorrect password + Incorrect login or password error.sql_login diff --git a/translations/messages.fr.xlf b/translations/messages.fr.xlf index 662608c..39a5e8d 100644 --- a/translations/messages.fr.xlf +++ b/translations/messages.fr.xlf @@ -7,11 +7,7 @@ error.login - Login incorrect ou inconnu - - - error.password - Mot de passe incorrect + Login ou mot de passe inconnu error.sql_login -- 2.17.1 From 51c92a0dba60bf9c2f55cca56959e27ff0f4ba45 Mon Sep 17 00:00:00 2001 From: rudy Date: Mon, 29 Apr 2024 11:09:58 +0200 Subject: [PATCH 4/4] feat (gestion exception) #19: modification fetchPassword --- src/Controller/SecurityController.php | 6 +- src/Security/SQLLoginUserAuthenticator.php | 64 +++++++++++----------- src/Service/SQLLoginService.php | 17 +++--- 3 files changed, 43 insertions(+), 44 deletions(-) diff --git a/src/Controller/SecurityController.php b/src/Controller/SecurityController.php index 6e4b75b..71fd3de 100644 --- a/src/Controller/SecurityController.php +++ b/src/Controller/SecurityController.php @@ -17,7 +17,7 @@ use Symfony\Contracts\Translation\TranslatorInterface; class SecurityController extends AbstractController { #[Route('/login', name: 'app_login')] - public function login(ParameterBagInterface $params, AuthenticationUtils $authenticationUtils, Request $request, TranslatorInterface $trans): Response + public function login(ParameterBagInterface $params, AuthenticationUtils $authenticationUtils, Request $request, TranslatorInterface $trans): Response|RedirectResponse { // Si l'utilisateur est déjà connecté on le renvoie sur la page du site demandeur if ($this->getUser()) { @@ -32,10 +32,6 @@ class SecurityController extends AbstractController $loginForm->addError(new FormError($trans->trans('error.login', [], 'messages'))); $request->getSession()->remove(SQLLoginUserAuthenticator::ERROR_LOGIN); } - if ($request->getSession()->has(SQLLoginUserAuthenticator::ERROR_PASSWORD)) { - $loginForm->addError(new FormError($trans->trans('error.login', [], 'messages'))); - $request->getSession()->remove(SQLLoginUserAuthenticator::ERROR_PASSWORD); - } if ($request->getSession()->has(SQLLoginUserAuthenticator::ERROR_PDO)) { $loginForm->addError(new FormError($trans->trans('error.pdo', [], 'messages'))); $request->getSession()->remove(SQLLoginUserAuthenticator::ERROR_PDO); diff --git a/src/Security/SQLLoginUserAuthenticator.php b/src/Security/SQLLoginUserAuthenticator.php index 5db74cc..6670214 100644 --- a/src/Security/SQLLoginUserAuthenticator.php +++ b/src/Security/SQLLoginUserAuthenticator.php @@ -10,6 +10,7 @@ use App\SQLLogin\Exception\DataToFetchConfigurationException; use App\SQLLogin\Exception\InvalidSQLPasswordException; use App\SQLLogin\Exception\LoginElementsConfigurationException; use App\SQLLogin\Exception\SecurityPatternConfigurationException; +use Exception; use Symfony\Component\HttpFoundation\RedirectResponse; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; @@ -24,7 +25,6 @@ class SQLLoginUserAuthenticator extends AbstractLoginFormAuthenticator { public const LOGIN_ROUTE = 'app_login'; public const ERROR_LOGIN = 'error_login'; - public const ERROR_PASSWORD = 'error_password'; public const ERROR_PDO = 'error_pdo'; public const ERROR_SQL_LOGIN = 'error_sql_login'; public const ERROR_CONFIGURATION = 'error_configuration'; @@ -80,40 +80,42 @@ class SQLLoginUserAuthenticator extends AbstractLoginFormAuthenticator } catch (LoginElementsConfigurationException $e) { $session->set(self::ERROR_CONFIGURATION, true); throw new AuthenticationException(); + } catch (Exception $exception) { + $request->getSession()->set(self::ERROR_LOGIN, true); + throw new AuthenticationException(); } - if ($remoteHashedPassword) { - try { - // Comparaison remote hash et hash du input password + salt - $this->passwordHasher->verify($remoteHashedPassword, $plaintextPassword, $remoteSalt); - $attributes = $this->sqlLoginService->fetchDatas($login); - $user = new User($login, $remoteHashedPassword, $attributes, $rememberMe); + if (!$remoteHashedPassword) { + throw new Exception('Erreur inconnue'); + } + try { + // Comparaison remote hash et hash du input password + salt + $this->passwordHasher->verify($remoteHashedPassword, $plaintextPassword, $remoteSalt); + $attributes = $this->sqlLoginService->fetchDatas($login); + $user = new User($login, $remoteHashedPassword, $attributes, $rememberMe); - $loader = function (string $userIdentifier) use ($user) { - return $user->getLogin() == $userIdentifier ? $user : null; - }; - $passport = new SelfValidatingPassport(new UserBadge($login, $loader)); - if ($rememberMe) { - $passport->addBadge(new RememberMeBadge()); - } - $passport->setAttribute('attributes', $user->getAttributes()); - - return $passport; - } catch (InvalidSQLPasswordException $e) { - $session->set(self::ERROR_PASSWORD, true); - throw new AuthenticationException(); - } catch (DataToFetchConfigurationException $e) { - $session->set(self::ERROR_DATA_TO_FETCH_CONFIGURATION, true); - throw new AuthenticationException(); - } catch (DatabaseConnectionException $e) { - $session->set(self::ERROR_PDO, true); - throw new AuthenticationException(); - } catch (SecurityPatternConfigurationException $e) { - $session->set(self::ERROR_SECURITY_PATTERN_CONFIGURATION, true); - throw new AuthenticationException(); + $loader = function (string $userIdentifier) use ($user) { + return $user->getLogin() == $userIdentifier ? $user : null; + }; + $passport = new SelfValidatingPassport(new UserBadge($login, $loader)); + if ($rememberMe) { + $passport->addBadge(new RememberMeBadge()); } + $passport->setAttribute('attributes', $user->getAttributes()); + + return $passport; + } catch (InvalidSQLPasswordException $e) { + $session->set(self::ERROR_LOGIN, true); + throw new AuthenticationException(); + } catch (DataToFetchConfigurationException $e) { + $session->set(self::ERROR_DATA_TO_FETCH_CONFIGURATION, true); + throw new AuthenticationException(); + } catch (DatabaseConnectionException $e) { + $session->set(self::ERROR_PDO, true); + throw new AuthenticationException(); + } catch (SecurityPatternConfigurationException $e) { + $session->set(self::ERROR_SECURITY_PATTERN_CONFIGURATION, true); + throw new AuthenticationException(); } - $request->getSession()->set(self::ERROR_LOGIN, true); - throw new AuthenticationException(); } protected function getLoginUrl(Request $request): string diff --git a/src/Service/SQLLoginService.php b/src/Service/SQLLoginService.php index ece37cb..2011d60 100644 --- a/src/Service/SQLLoginService.php +++ b/src/Service/SQLLoginService.php @@ -8,6 +8,7 @@ use App\SQLLogin\Exception\LoginElementsConfigurationException; use App\SQLLogin\Exception\NullDataToFetchException; use App\SQLLogin\SQLLoginConnect; use App\SQLLogin\SQLLoginRequest; +use Exception; use PDO; use PDOException; use Psr\Log\LoggerInterface; @@ -51,7 +52,7 @@ class SQLLoginService extends AbstractController return $datas; } - public function fetchPassword($login): array|bool + public function fetchPassword(string $login): array { try { $dbh = $this->getConnection(); @@ -71,14 +72,14 @@ class SQLLoginService extends AbstractController $this->loggerInterface->critical($e->getMessage()); throw new LoginElementsConfigurationException($e->getMessage()); } - if ($password) { - return [ - $password[$this->sqlLoginRequest->getPasswordColumnName()], - isset($password[$this->sqlLoginRequest->getSaltColumnName()]) ? $password[$this->sqlLoginRequest->getSaltColumnName()] : null, - ]; + if (!$password) { + throw new Exception('Une erreur est survenue lors de la récupération des données'); } - - return false; + + return [ + $password[$this->sqlLoginRequest->getPasswordColumnName()], + isset($password[$this->sqlLoginRequest->getSaltColumnName()]) ? $password[$this->sqlLoginRequest->getSaltColumnName()] : null, + ]; } public function getConnection(): PDO -- 2.17.1