<?php
namespace App\EventListener;
use App\Entity\Device;
use App\Entity\User;
use App\Entity\UserDeviceToken;
use App\Entity\UserProfile;
use Doctrine\ORM\EntityManagerInterface;
use Lexik\Bundle\JWTAuthenticationBundle\Event\AuthenticationSuccessEvent;
use Lexik\Bundle\JWTAuthenticationBundle\Event\AuthenticationFailureEvent;
use Lexik\Bundle\JWTAuthenticationBundle\Services\JWTTokenManagerInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\RequestStack;
class AuthenticationSuccessListener
{
private $em;
private $jwtManager;
public function __construct(EntityManagerInterface $em, JWTTokenManagerInterface $jwtManager,RequestStack $requestStack)
{
$this->em = $em;
$this->jwtManager = $jwtManager;
$this->requestStack = $requestStack;
}
public function onAuthenticationSuccess(AuthenticationSuccessEvent $event)
{
$request = $this->requestStack->getCurrentRequest();
$requestData = json_decode($request->getContent(), true);
$params['system_language'] = $requestData['system_language'] ?? 'uk';
$params['deviceToken'] = $requestData['device_token'] ?? '';
$data = $event->getData();
$user = $event->getUser();
if(property_exists($user, 'isVerified') && !$user->getIsVerified()){
$event->setData([
'status'=>'failed','message'=>'Email not verified'
]);
return true;
}
// Fetch user profile data
$userProfileData = $this->em->getRepository(UserProfile::class)->getUserDetailsWithIdOrName(['userName'=> $user?->getUserName()]);
// Generate a new JWT token
$user = $this->em->getRepository(User::class)->findOneBy(['userName' => $user?->getUserName()]);
$userId = $params['user_id'] = $user->getId();
$params['status'] = '1';
//Fetch devices
$deviceCount = $this->em->getRepository(UserProfile::class)->getDeviceCount($userId);
if(!empty($params['deviceToken'])){
$checkDeviceExist = $this->em->getRepository(UserDeviceToken::class)->checkDeviceExist($params);
if(empty($checkDeviceExist)){
$saveUserDevice = $this->em->getRepository(UserDeviceToken::class)->saveUserDeviceData($params);
}
}
//update user system language
if(!empty($params['system_language'])){
$this->em->getRepository(User::class)->updateUserSystemLanguage($params);
}
// Add additional parameters to the response data
$data = [
'status' => 'success',
'message' => 'Login successfully',
'data' => [
'user_id' => $user->getId(),
'username' => $user->getUserName(),
'email' => $user->getEmail(),
'profile_image' => $userProfileData['profileImage'],
'contact_number' => $userProfileData['contactNumber'],
'first_name' => $userProfileData['firstName'],
'last_name' => $userProfileData['lastName'],
'deviceCount' => (string)$deviceCount,
],
'token' => $this->jwtManager->create($user)
];
$event->setData($data);
}
public function onAuthenticationFailure(AuthenticationFailureEvent $event)
{
$data = [
'status' => 'failure',
'message' => 'Incorrect credentials'
];
$response = new JsonResponse($data);
$event->setResponse($response);
}
}