This repository has been archived on 2024-10-16. You can view files and clone it, but cannot push or open issues or pull requests.
pflaenz.li-Symfony/src/Security/AppAuthenticator.php

60 lines
2.1 KiB
PHP
Raw Normal View History

2021-04-22 15:20:02 +02:00
<?php
namespace App\Security;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
2021-09-14 14:03:27 +02:00
use Symfony\Component\HttpFoundation\Response;
2021-04-22 15:20:02 +02:00
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Security;
2021-09-14 14:03:27 +02:00
use Symfony\Component\Security\Http\Authenticator\AbstractLoginFormAuthenticator;
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\CsrfTokenBadge;
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\UserBadge;
use Symfony\Component\Security\Http\Authenticator\Passport\Credentials\PasswordCredentials;
use Symfony\Component\Security\Http\Authenticator\Passport\Passport;
use Symfony\Component\Security\Http\Authenticator\Passport\PassportInterface;
2021-04-22 15:20:02 +02:00
use Symfony\Component\Security\Http\Util\TargetPathTrait;
2021-09-14 14:03:27 +02:00
class AppAuthenticator extends AbstractLoginFormAuthenticator
2021-04-22 15:20:02 +02:00
{
use TargetPathTrait;
public const LOGIN_ROUTE = 'app_login';
2021-09-14 14:03:27 +02:00
private UrlGeneratorInterface $urlGenerator;
2021-04-22 15:20:02 +02:00
2021-09-14 14:03:27 +02:00
public function __construct(UrlGeneratorInterface $urlGenerator)
2021-04-22 15:20:02 +02:00
{
$this->urlGenerator = $urlGenerator;
}
2021-09-14 14:03:27 +02:00
public function authenticate(Request $request): PassportInterface
2021-04-22 15:20:02 +02:00
{
2021-09-14 14:03:27 +02:00
$email = $request->request->get('email', '');
2021-04-22 15:20:02 +02:00
2021-09-14 14:03:27 +02:00
$request->getSession()->set(Security::LAST_USERNAME, $email);
2021-04-22 15:20:02 +02:00
2021-09-14 14:03:27 +02:00
return new Passport(
new UserBadge($email),
new PasswordCredentials($request->request->get('password', '')),
[
new CsrfTokenBadge('authenticate', $request->get('_csrf_token')),
]
);
2021-04-22 15:20:02 +02:00
}
2021-09-14 14:03:27 +02:00
public function onAuthenticationSuccess(Request $request, TokenInterface $token, string $firewallName): ?Response
2021-04-22 15:20:02 +02:00
{
2021-09-14 14:03:27 +02:00
if ($targetPath = $this->getTargetPath($request->getSession(), $firewallName)) {
2021-04-22 15:20:02 +02:00
return new RedirectResponse($targetPath);
}
2021-04-23 15:16:06 +02:00
return new RedirectResponse($this->urlGenerator->generate('user_page'));
2021-04-22 15:20:02 +02:00
}
2021-09-14 14:03:27 +02:00
protected function getLoginUrl(Request $request): string
2021-04-22 15:20:02 +02:00
{
return $this->urlGenerator->generate(self::LOGIN_ROUTE);
}
2021-09-14 14:03:27 +02:00
}