<?php
namespace App\EventSubscriber;
use App\Entity\Association;
use App\Entity\Award;
use App\Entity\Objective;
use App\Entity\Company;
use App\Entity\Department;
use App\Entity\Log;
use App\Entity\MediaObject;
use App\Entity\User;
use Doctrine\ORM\EntityManagerInterface;
use Lexik\Bundle\JWTAuthenticationBundle\Event\JWTCreatedEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Lexik\Bundle\JWTAuthenticationBundle\Event\AuthenticationSuccessEvent as JWTSuccessAuth;
use Lexik\Bundle\JWTAuthenticationBundle\Events as JWTEvents;
use Symfony\Component\HttpFoundation\RequestStack;
/**
* Logs actions associated with the users, when the connect and when they disconnect
* Class LoginEventSubscriber
* @package App\EventSubscriber
*/
class LoginEventSubscriber implements EventSubscriberInterface
{
const MESSAGES = [
'success' => 'User is logged in'
];
/**
* @var EntityManagerInterface
*/
private $manager;
/**
* @var int|string
*/
private $tokenTtl;
/**
* LoginEventSubscriber constructor.
* @param EntityManagerInterface $manager
*/
public function __construct(EntityManagerInterface $manager, $tokenTtl)
{
$this->manager = $manager;
$this->tokenTtl = $tokenTtl;
}
/**
* {@inheritDoc}
*/
public static function getSubscribedEvents(): array
{
// return the subscribed events, their methods and priorities
return [
JWTEvents::AUTHENTICATION_SUCCESS => [
['logUserConnection', 0],
],
JWTEvents::JWT_CREATED => [
['onJWTCreatedAddDataToPayload', 0],
],
];
}
/**
* Sets the company user on the payload
* @param JWTCreatedEvent $event
*/
public function onJWTCreatedAddDataToPayload(JWTCreatedEvent $event)
{
$user = $event->getUser();
$payload = $event->getData();
if ($user instanceof User) {
$payload['email'] = $user->getEmail();
$payload['id'] = $user->getId();
$payload['firstLogin'] = $user->isFirstLogin();
$payload['homeSurvey'] = $user->isHomeSurvey();
if($user->getDepartment() instanceof Department) {
$department = $user->getDepartment();
$payload['department'] = [
'id' => $department->getId(),
'name' => $department->getName()
];
}
$payload['rmbKey'] = sha1($user->getUsername().$user->getPassword());
// Add Company info into JWT
if ($user->getCompany() instanceof Company) {
$company = $user->getCompany();
// Vérifie si les associations sont actives
$isAssociative = false;
if(!empty($company->getAssociations()->toArray())) {
foreach ($company->getAssociations()->toArray() as $association) {
if($association->getActive() == 1) {
$isAssociative = true;
break;
}
}
}
$company_arr = [
'id' => $company->getId(),
'name' => $company->getName(),
'logo' => ($company->getLogo() instanceof MediaObject) ? $company->getLogo()->getContentUrl() : null,
'cmsTitle' => urlencode($company->getCmsTitle()),
'cmsText' => urlencode($company->getCmsText()),
'cmsImg' => ($company->getCmsImg() instanceof MediaObject) ? $company->getCmsImg()->getContentUrl() : null,
'cmsCtaText' => $company->getCmsCtaText(),
'cmsCtaUrl' => $company->getCmsCtaUrl(),
'isAssociative' => $isAssociative,
'isResa' => $company->getResaLinkActive(),
];
$payload['company'] = $company_arr;
if (!$user->hasRole('ROLE_MANAGER')){
// $expiration = (!empty($user->getCompany()) ?
// $user->getCompany()->getNextRestriction(new \DateTime(), new \DateTime("+ {$this->tokenTtl} seconds")) : null);
// if ($expiration instanceof \DateTime) {
// $payload['exp'] = $expiration->getTimestamp();
// }
}
}
// Add displayObjectiveSurvey
// $user_interests = $this->manager->getRepository(Objective::class)->customFindBy(['userId' => $user->getId(), 'active' => 1]);
$payload['displayObjectiveSurvey'] = (!empty($user->getObjectives()->toArray())) ? false : true;
$payload['isAwardEvent'] = false;
$award = $this->manager->getRepository(Award::class)->getActiveAwardsBy(['user' => $user], ['dateEnd' => "ASC"], 1);
if(!empty($award)) $payload['isAwardEvent'] = true;
$payload['isAssociation'] = ($user->getAssociation() instanceof Association && $user->getAssociation()->getActive() == 1) ? true : false;
}
$event->setData($payload);
}
/**
* Logs the user connection in the db
* @param JWTSuccessAuth $event
*/
public function logUserConnection(JWTSuccessAuth $event)
{
$user = $event->getUser();
if ($user instanceof User) {
$log = new Log();
$log
->setCategory(Log::CATEGORY_LOGIN_EVENT)
->setSubCategory(Log::SUB_LOGIN_SUCCESS)
->setMessage(self::MESSAGES['success'])
->setUser($user);
$user->setLastLogin(new \DateTime());
$this->manager->persist($log);
$this->manager->persist($user);
$this->manager->flush();
}
}
}