<?php
namespace App\EventSubscriber;
use App\Entity\Client;
use App\Entity\Company;
use App\Entity\Log;
use App\Entity\MediaObject;
use App\Entity\Segmentation;
use App\Entity\Specialist;
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;
/**
* 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 $em;
/**
* @var int|string
*/
private $tokenTtl;
/**
* LoginEventSubscriber constructor.
* @param EntityManagerInterface $em
*/
public function __construct(EntityManagerInterface $em, $tokenTtl)
{
$this->em = $em;
$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 data's user on the payload
* @param JWTCreatedEvent $event
* @return void
*/
public function onJWTCreatedAddDataToPayload(JWTCreatedEvent $event)
{
$user = $event->getUser();
$payload = $event->getData();
if ($user instanceof User) {
$payload['id'] = $user->getId();
$payload['email'] = $user->getEmail();
$payload['segmentation'] = null;
if($user->getClient() instanceof Client && $user->hasRole(User::ROLE_CLIENT)) {
$client = $user->getClient();
$payload['client'] = [
'id' => $client->getId(),
'firstname' => $client->getFirstName(),
'lastname' => $client->getLastName(),
];
if($user->getSegmentation() instanceof Segmentation) {
$segmentation = $user->getSegmentation();
$payload['segmentation'] = [
'id' => $segmentation->getId(),
'name' => $segmentation->getName()
];
}
if ($client->getCompany() instanceof Company) {
$company = $client->getCompany();
$payload['company'] = [
'id' => $company->getId(),
'name' => $company->getName(),
'logoTv' => ($company->getLogo() instanceof MediaObject) ? $company->getLogo()->getContentUrl() : null,
'logo' => $company->getImageUrl(),
'imageUrl' => $company->getImageUrl(),
'forceSegmentation' => $company->getForceSegmentation(),
'hasSegmentations' => ($company->getSegmentations()->count() > 0) ? true : false,
// 'cmsTitle' => urlencode($company->getCmsTitle()),
// 'cmsText' => urlencode($company->getCmsText()),
// 'cmsImg' => ($company->getCmsImg() instanceof MediaObject) ? $company->getCmsImg()->getContentUrl() : null,
// 'cmsCtaText' => $company->getCmsCtaText(),
// 'cmsCtaUrl' => $company->getCmsCtaUrl(),
// 'isAssociative' => $company->isActiveAssociation(),
];
// if (!$user->hasRole(User::ROLE_COMPANY)){
// $expiration = (!empty($user->getCompany()) ?
// $user->getCompany()->getNextRestriction(new \DateTime(), new \DateTime("+ {$this->tokenTtl} seconds")) : null);
// if ($expiration instanceof \DateTime) {
// $payload['exp'] = $expiration->getTimestamp();
// }
// }
}
// $payload['isAssociation'] = ($client->getAssociation() instanceof Association && $client->getAssociation()->getActive() == 1) ? true : false;
$payload['isFirstLogin'] = $user->isFirstLogin();
// $payload['isHomeSurvey'] = $user->isHomeSurvey();
$payload['rmbKey'] = sha1($user->getUsername().$user->getPassword());
// Add displayObjectiveSurvey
// $user_interests = $this->em->getRepository(Objective::class)->customFindBy(['userId' => $user->getId(), 'active' => 1]);
// $payload['displayObjectiveSurvey'] = (!empty($user->getObjectives()->toArray())) ? false : true;
// $payload['isAwardEvent'] = false;
// /**
// * @var AwardRepository
// */
// $awardRepo = $this->em->getRepository(Award::class);
// $award = $awardRepo->getActiveAwardsBy(['user' => $user], ['dateEnd' => "ASC"], 1);
// if(!empty($award)) $payload['isAwardEvent'] = true;
// $payload['isLive'] = $user->isLive();
// $payload['isTv'] = $user->isTv();
}
if($user->getCompany() instanceof Company && $user->hasRole(User::ROLE_COMPANY)) {
$payload['firstname'] = $user->getFirstName() ?? '';
$payload['lastname'] = $user->getLastName() ?? '';
$payload['function'] = $user->getFunction() ?? '';
$company = $user->getCompany();
$payload['company']['id'] = $company->getId();
$payload['company']['name'] = $company->getName();
$payload['company']['isLive'] = $company->isLive();
$payload['company']['iTv'] = $company->isTv();
}
if($user->getSpecialist() instanceof Specialist && $user->hasRole(User::ROLE_SPECIALIST)) {
$payload['firstname'] = $user->getFirstName() ?? '';
$payload['lastname'] = $user->getLastName() ?? '';
$specialist = $user->getSpecialist();
$payload['specialist']['id'] = $specialist->getId();
$payload['specialist']['firstname'] = $specialist->getFirstName();
$payload['specialist']['lastname'] = $specialist->getLastName();
}
}
$event->setData($payload);
}
/**
* Logs the user connection in the db
* @param JWTSuccessAuth $event
* @return void
*/
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->em->persist($log);
// $this->em->flush();
$this->em->persist($user);
$this->em->flush();
}
}
}