1 <?php
declare(strict_types
=1);
4 * This file is part of the Rapsys UserBundle package.
6 * (c) Raphaël Gertz <symfony@rapsys.eu>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Rapsys\UserBundle\Handler
;
14 use Doctrine\Persistence\ManagerRegistry
;
16 use Psr\Log\LoggerInterface
;
18 use Rapsys\PackBundle\Util\SluggerUtil
;
20 use Rapsys\UserBundle\Exception\UnactivatedException
;
21 use Rapsys\UserBundle\RapsysUserBundle
;
23 use Symfony\Bridge\Twig\Mime\TemplatedEmail
;
24 use Symfony\Component\DependencyInjection\ContainerInterface
;
25 use Symfony\Component\HttpFoundation\RedirectResponse
;
26 use Symfony\Component\HttpFoundation\Request
;
27 use Symfony\Component\HttpFoundation\RequestStack
;
28 use Symfony\Component\HttpFoundation\Response
;
29 use Symfony\Component\HttpFoundation\Session\FlashBagAwareSessionInterface
;
30 use Symfony\Component\HttpKernel\HttpKernelInterface
;
31 use Symfony\Component\Mailer\MailerInterface
;
32 use Symfony\Component\Mime\Address
;
33 use Symfony\Component\Routing\Exception\ResourceNotFoundException
;
34 use Symfony\Component\Routing\Generator\UrlGeneratorInterface
;
35 use Symfony\Component\Routing\RequestContext
;
36 use Symfony\Component\Routing\RouterInterface
;
37 use Symfony\Component\Security\Core\Exception\AuthenticationException
;
38 use Symfony\Component\Security\Core\Exception\BadCredentialsException
;
39 use Symfony\Component\Security\Core\Exception\DisabledException
;
40 use Symfony\Component\Security\Core\Exception\UserNotFoundException
;
41 use Symfony\Component\Security\Http\Authentication\DefaultAuthenticationFailureHandler
;
42 use Symfony\Component\Security\Http\HttpUtils
;
43 use Symfony\Contracts\Translation\TranslatorInterface
;
48 class AuthenticationFailureHandler
extends DefaultAuthenticationFailureHandler
{
52 protected string $alias;
57 protected array $config;
58 protected array $defaultOptions = [
59 'failure_path' => null,
60 'failure_forward' => false,
61 'login_path' => '/login',
62 'failure_path_parameter' => '_failure_path',
68 * @xxx Second argument will be replaced by security.firewalls.main.logout.target
69 * @see vendor/symfony/security-bundle/DependencyInjection/SecurityExtension.php +360
71 * @param HttpKernelInterface $httpKernel The http kernel
72 * @param HttpUtils $httpUtils The http utils
73 * @param array $options The options
74 * @param LoggerInterface $logger The logger instance
75 * @param ?string $firewallName The firewall name
76 * @param ContainerInterface $container The container instance
77 * @param ManagerRegistry $doctrine The doctrine instance
78 * @param MailerInterface $mailer The mailer instance
79 * @param RouterInterface $router The router instance
80 * @param SluggerUtil $slugger The slugger instance
81 * @param RequestStack $stack The stack instance
82 * @param TranslatorInterface $translator The translator instance
84 public function __construct(protected HttpKernelInterface
$httpKernel, protected HttpUtils
$httpUtils, protected array $options, protected ?LoggerInterface
$logger, private readonly
?string $firewallName, protected ContainerInterface
$container, protected ManagerRegistry
$doctrine, protected MailerInterface
$mailer, protected RouterInterface
$router, protected SluggerUtil
$slugger, protected RequestStack
$stack, protected TranslatorInterface
$translator) {
85 //Call parent constructor
86 parent
::__construct($httpKernel, $httpUtils, $options, $logger, $firewallName);
89 $this->config
= $container->getParameter($this->alias
= RapsysUserBundle
::getAlias());
93 * Adds a flash message to the current session for type.
95 * @throws \LogicException
97 protected function addFlash(string $type, mixed $message): void {
99 $session = $this->stack
->getSession();
100 } catch (SessionNotFoundException
$e) {
101 throw new \
LogicException('You cannot use the addFlash method if sessions are disabled. Enable them in "config/packages/framework.yaml".', 0, $e);
104 if (!$session instanceof FlashBagAwareSessionInterface
) {
105 throw new \
LogicException(sprintf('You cannot use the addFlash method because class "%s" doesn\'t implement "%s".', get_debug_type($session), FlashBagAwareSessionInterface
::class));
108 $session->getFlashBag()->add($type, $message);
114 * This is called when an interactive authentication attempt fails
116 public function onAuthenticationFailure(Request
$request, AuthenticationException
$exception): Response
{
117 //With bad credential exception
118 if ($exception instanceof BadCredentialsException
) {
119 //With parent exception
120 if (($parent = $exception->getPrevious()) instanceof UserNotFoundException
) {
121 /** Disabled to prevent user mail + hash retrieval for each unactivated/locked accounts
123 //Get user identifier
124 $mail = $parent->getUserIdentifier();
126 //Set extra parameters
127 $extra = ['mail' => $smail = $this->slugger->short($mail), 'hash' => $this->slugger->hash($smail)];*/
129 //With failure target path option
130 if (!empty($failurePath = $this->options
['failure_path'])) {
132 if ($failurePath[0] == '/') {
133 //Create login path request instance
134 $req = Request
::create($failurePath);
136 //Get login path pathinfo
137 $path = $req->getPathInfo();
140 $path = str_replace($request->getScriptName(), '', $path);
142 //Try with login path path
145 $oldContext = $this->router
->getContext();
147 //Force clean context
148 //XXX: prevent MethodNotAllowedException on GET only routes because our context method is POST
149 //XXX: see vendor/symfony/routing/Matcher/Dumper/CompiledUrlMatcherTrait.php +42
150 $this->router
->setContext(new RequestContext());
152 //Retrieve route matching path
153 $route = $this->router
->match($path);
156 $this->router
->setContext($oldContext);
162 if ($name = $route['_route']) {
163 //Remove route and controller from route defaults
164 unset($route['_route'], $route['_controller'], $route['_canonical_route']);
167 $url = $this->router
->generate($name, /*$extra+*/$route);
169 //Return redirect to url response
170 return new RedirectResponse($url, 302);
173 } catch (ResourceNotFoundException
$e) {
174 //Unset default path, name and route
175 unset($failurePath, $name, $route);
179 //Try with login path route
181 //Retrieve route matching path
182 $url = $this->router
->generate($failurePath/*, $extra*/);
184 //Return redirect to url response
185 return new RedirectResponse($url, 302);
186 //Route not found, missing parameter or invalid parameter
187 } catch (RouteNotFoundException
|MissingMandatoryParametersException
|InvalidParameterException
$e) {
188 //Unset default path and url
189 unset($failurePath, $url);
193 //With not enabled user
194 } elseif ($parent instanceof DisabledException
) {
195 //Add error message account is not enabled
196 $this->addFlash('error', $this->translator
->trans('Account not enabled', [], $this->alias
));
198 //Redirect on the same route with sent=1 to cleanup form
199 return new RedirectResponse($this->router
->generate($request->get('_route'), $request->get('_route_params')), 302);
200 //With not activated user
201 } elseif ($parent instanceof UnactivatedException
) {
203 $user = $parent->getUser();
207 'recipient_mail' => $user->getMail(),
208 'recipient_name' => $user->getRecipientName()
209 ] +
array_replace_recursive(
210 $this->config
['context'],
211 $this->config
['register']['view']['context'],
212 $this->config
['register']['mail']['context']
215 //Generate each route route
216 foreach($this->config
['register']['route'] as $route => $tag) {
217 //Only process defined routes
218 if (!empty($this->config
['route'][$route])) {
219 //Process for confirm url
220 if ($route == 'confirm') {
221 //Set the url in context
222 $context[$tag] = $this->router
->generate(
223 $this->config
['route'][$route]['name'],
224 //Prepend confirm context with tag
226 'mail' => $smail = $this->slugger
->short($context['recipient_mail']),
227 'hash' => $this->slugger
->hash($smail)
228 ]+
$this->config
['route'][$route]['context'],
229 UrlGeneratorInterface
::ABSOLUTE_URL
235 //Iterate on keys to translate
236 foreach($this->config
['translate'] as $translate) {
238 $keys = explode('.', $translate);
241 $current =& $context;
243 //Iterate on each subkey
245 //Skip unset translation keys
246 if (!isset($current[current($keys)])) {
250 //Set current to subkey
251 $current =& $current[current($keys)];
252 } while(next($keys));
255 $current = $this->translator
->trans($current, [], $this->alias
);
262 $context['subject'] = $subject = ucfirst(
263 $this->translator
->trans(
264 $this->config
['register']['mail']['subject'],
265 $this->slugger
->flatten($context, null, '.', '%', '%'),
271 $message = (new TemplatedEmail())
273 ->from(new Address($this->config
['contact']['address'], $this->config
['contact']['name']))
275 //XXX: remove the debug set in vendor/symfony/mime/Address.php +46
276 ->to(new Address($context['recipient_mail'], $context['recipient_name']))
278 ->subject($context['subject'])
280 //Set path to twig templates
281 ->htmlTemplate($this->config
['register']['mail']['html'])
282 ->textTemplate($this->config
['register']['mail']['text'])
287 //Try sending message
288 //XXX: mail delivery may silently fail
291 $this->mailer
->send($message);
292 //Catch obvious transport exception
293 } catch(TransportExceptionInterface
$e) {
294 //Add error message mail unreachable
295 $this->addFlash('error', $this->translator
->trans('Unable to reach account', [], $this->alias
));
299 $this->addFlash('notice', $this->translator
->trans('Your verification mail has been sent, to activate your account follow the confirmation link inside', [], $this->alias
));
302 $this->addFlash('warning', $this->translator
->trans('If you did not receive a verification mail, check your Spam or Junk mail folder', [], $this->alias
));
304 //Redirect on the same route with sent=1 to cleanup form
305 return new RedirectResponse($this->router
->generate($request->get('_route'), $request->get('_route_params')), 302);
309 //Call parent function
310 return parent
::onAuthenticationFailure($request, $exception);