<?php declare(strict_types=1);
namespace App\Authentication\EventListener;
use App\Authentication\Entity\User;
use App\Customer\Service\CustomerService;
use App\Employee\Service\EmployeeService;
use Doctrine\ORM\EntityNotFoundException;
use Lexik\Bundle\JWTAuthenticationBundle\Event\AuthenticationSuccessEvent;
use Symfony\Component\Security\Core\User\UserInterface;
class JWTAuthenticationSuccessListener
{
private CustomerService $customerService;
private EmployeeService $employeeService;
public function __construct(CustomerService $customerService, EmployeeService $employeeService)
{
$this->customerService = $customerService;
$this->employeeService = $employeeService;
}
public function onAuthenticationSuccessResponse(AuthenticationSuccessEvent $event): void
{
$data = $event->getData();
$user = $event->getUser();
if (!$user instanceof UserInterface) {
return;
}
/** @var User $user */
$data['id'] = $user->getId();
$data['roles'] = $user->getRoles();
$customer = null;
$employee = null;
try {
$customer = $this->customerService->getByUser($user);
} catch (EntityNotFoundException) {
// entirely ok
}
try {
$employee = $this->employeeService->getByUser($user);
} catch (EntityNotFoundException) {
// entirely ok
}
if ($employee !== null) {
$data['employee_id'] = $employee->getId();
$data['firstName'] = $employee->getFirstName();
} elseif ($customer !== null) {
$data['customer_id'] = $customer->getId();
$data['firstName'] = $customer->getFirstName();
}
$event->setData($data);
}
}