]> Raphaël G. Git Repositories - userbundle/blob - Handler/AuthenticationFailureHandler.php
Version 0.6.1
[userbundle] / Handler / AuthenticationFailureHandler.php
1 <?php declare(strict_types=1);
2
3 /*
4 * This file is part of the Rapsys UserBundle package.
5 *
6 * (c) Raphaël Gertz <symfony@rapsys.eu>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12 namespace Rapsys\UserBundle\Handler;
13
14 use Doctrine\Persistence\ManagerRegistry;
15
16 use Psr\Log\LoggerInterface;
17
18 use Rapsys\PackBundle\Util\SluggerUtil;
19
20 use Rapsys\UserBundle\Exception\UnactivatedException;
21 use Rapsys\UserBundle\RapsysUserBundle;
22
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;
44
45 /**
46 * {@inheritdoc}
47 */
48 class AuthenticationFailureHandler extends DefaultAuthenticationFailureHandler {
49 /**
50 * Alias string
51 */
52 protected string $alias;
53
54 /**
55 * Config array
56 */
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',
63 ];
64
65 /**
66 * {@inheritdoc}
67 *
68 * @xxx Second argument will be replaced by security.firewalls.main.logout.target
69 * @see vendor/symfony/security-bundle/DependencyInjection/SecurityExtension.php +360
70 *
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
83 */
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);
87
88 //Set config
89 $this->config = $container->getParameter($this->alias = RapsysUserBundle::getAlias());
90 }
91
92 /**
93 * Adds a flash message to the current session for type.
94 *
95 * @throws \LogicException
96 */
97 protected function addFlash(string $type, mixed $message): void {
98 try {
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);
102 }
103
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));
106 }
107
108 $session->getFlashBag()->add($type, $message);
109 }
110
111 /**
112 * {@inheritdoc}
113 *
114 * This is called when an interactive authentication attempt fails
115 */
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
122
123 //Get user identifier
124 $mail = $parent->getUserIdentifier();
125
126 //Set extra parameters
127 $extra = ['mail' => $smail = $this->slugger->short($mail), 'hash' => $this->slugger->hash($smail)];*/
128
129 //With failure target path option
130 if (!empty($failurePath = $this->options['failure_path'])) {
131 //With path
132 if ($failurePath[0] == '/') {
133 //Create login path request instance
134 $req = Request::create($failurePath);
135
136 //Get login path pathinfo
137 $path = $req->getPathInfo();
138
139 //Remove script name
140 $path = str_replace($request->getScriptName(), '', $path);
141
142 //Try with login path path
143 try {
144 //Save old context
145 $oldContext = $this->router->getContext();
146
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());
151
152 //Retrieve route matching path
153 $route = $this->router->match($path);
154
155 //Reset context
156 $this->router->setContext($oldContext);
157
158 //Clear old context
159 unset($oldContext);
160
161 //With route name
162 if ($name = $route['_route']) {
163 //Remove route and controller from route defaults
164 unset($route['_route'], $route['_controller'], $route['_canonical_route']);
165
166 //Generate url
167 $url = $this->router->generate($name, /*$extra+*/$route);
168
169 //Return redirect to url response
170 return new RedirectResponse($url, 302);
171 }
172 //No route matched
173 } catch (ResourceNotFoundException $e) {
174 //Unset default path, name and route
175 unset($failurePath, $name, $route);
176 }
177 //With route name
178 } else {
179 //Try with login path route
180 try {
181 //Retrieve route matching path
182 $url = $this->router->generate($failurePath/*, $extra*/);
183
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);
190 }
191 }
192 }
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));
197
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) {
202 //Set user
203 $user = $parent->getUser();
204
205 //Set context
206 $context = [
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']
213 );
214
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
225 [
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
230 );
231 }
232 }
233 }
234
235 //Iterate on keys to translate
236 foreach($this->config['translate'] as $translate) {
237 //Extract keys
238 $keys = explode('.', $translate);
239
240 //Set current
241 $current =& $context;
242
243 //Iterate on each subkey
244 do {
245 //Skip unset translation keys
246 if (!isset($current[current($keys)])) {
247 continue(2);
248 }
249
250 //Set current to subkey
251 $current =& $current[current($keys)];
252 } while(next($keys));
253
254 //Set translation
255 $current = $this->translator->trans($current, [], $this->alias);
256
257 //Remove reference
258 unset($current);
259 }
260
261 //Translate subject
262 $context['subject'] = $subject = ucfirst(
263 $this->translator->trans(
264 $this->config['register']['mail']['subject'],
265 $this->slugger->flatten($context, null, '.', '%', '%'),
266 $this->alias
267 )
268 );
269
270 //Create message
271 $message = (new TemplatedEmail())
272 //Set sender
273 ->from(new Address($this->config['contact']['address'], $this->config['contact']['name']))
274 //Set recipient
275 //XXX: remove the debug set in vendor/symfony/mime/Address.php +46
276 ->to(new Address($context['recipient_mail'], $context['recipient_name']))
277 //Set subject
278 ->subject($context['subject'])
279
280 //Set path to twig templates
281 ->htmlTemplate($this->config['register']['mail']['html'])
282 ->textTemplate($this->config['register']['mail']['text'])
283
284 //Set context
285 ->context($context);
286
287 //Try sending message
288 //XXX: mail delivery may silently fail
289 try {
290 //Send message
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));
296 }
297
298 //Add notice
299 $this->addFlash('notice', $this->translator->trans('Your verification mail has been sent, to activate your account follow the confirmation link inside', [], $this->alias));
300
301 //Add junk warning
302 $this->addFlash('warning', $this->translator->trans('If you did not receive a verification mail, check your Spam or Junk mail folder', [], $this->alias));
303
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);
306 }
307 }
308
309 //Call parent function
310 return parent::onAuthenticationFailure($request, $exception);
311 }
312 }