<?php
namespace App\EventListener;
use App\Entity\Company;
use App\Entity\LoginSessions;
use App\Entity\Terminology;
use App\Entity\UserProfile;
use App\Utils\LtsUtils;
use App\Utils\TopNavbar;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Security\Core\Security;
use Symfony\Contracts\Translation\TranslatorInterface;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpFoundation\Response;
final class RoutingListener
{
/**
* @var ContainerInterface
*/
private $container;
/**
* @var mixed;
*/
private $topNavbar;
/**
* @var LtsUtils;
*/
private $ltsUtils;
/**
* @var TranslatorInterface;
*/
private $translator;
/**
* @var Security;
*/
private $security;
/**
* @var mixed;
*/
private $parameters;
private $em;
private $router;
private $companyId;
/**
* Constructor.
*
* @param Container $container
*/
public function __construct(ContainerInterface $container, Security $security, EntityManagerInterface $entityManager, TopNavbar $topNavBar, LtsUtils $ltsUtils, TranslatorInterface $translator, RouterInterface $router)
{
$this->container = $container;
$this->security = $security;
$this->em = $entityManager;
$this->topNavbar = $topNavBar;
$this->ltsUtils = $ltsUtils;
$this->translator = $translator;
$this->router = $router;
$this->companyId = $this->container->getParameter('default_company_id');
}
/**
* Routing Listener event.
*/
public function onKernelRequest(RequestEvent $event)
{
$user = $this->security->getUser();
// Set default data
$this->setDefaultParams();
// Set UTC timezone
$this->setTimeZone();
if ($user) {
$this->setUserData($user);
$this->checkForPlanExpiry($event);
$this->checkUserPrevilage($user,$event);
$this->setTwigVariables();
$this->setCompanyDetails();
// Set company details
$this->translator->setLocale($this->parameters['lang']);
// Set container variables
$this->container->set('contact', $this);
// Set Top navigation details
$this->setTopNavLinks($event, $user);
// Set Demo tour details
$this->setDemoTourData();
// some logic to determine the $locale
// $request->setLocale('Asia/Kolkata');
// $this->saveLastActiveTime($event); # last activity time store
}
}
/**
* This function is to get contact data from contact object.
*
* @param string $key
*
* @return string
*/
public function get($key)
{
return $this->parameters[$key];
}
/**
* Method setDefaultParams
* This function is to set default contact data from contact object.
*
* @return void
*/
public function setDefaultParams()
{
$this->parameters['id'] = '';
$this->parameters['userId'] = '';
$this->parameters['email'] = '';
$this->parameters['firstName'] = '';
$this->parameters['surName'] = '';
$this->parameters['fullName'] = '';
$this->parameters['companyName'] = '';
$this->parameters['roles'] = '';
$this->parameters['isMainAdmin'] = '';
$this->parameters['profilePic'] = '';
$this->parameters['defaultDateFormat'] = 'd-m-Y h:i:a';
$this->parameters['defaultSystemLang'] = 'en';
$this->parameters['planExpireDate'] = null;
$this->parameters['plan'] = '';
$this->parameters['account_status'] = 'active';
$this->parameters['companyId'] = $this->companyId;
}
/**
* This function is to set contact details in contact object.
*
* @param object $user
*/
public function setUserData($user)
{
$userDetails = $this->em->getRepository(UserProfile::class)->getUserFullData($user->getId());
if ($userDetails) {
$this->parameters['id'] = $userDetails['id'];
$this->parameters['userId'] = $userDetails['id'];
$this->parameters['firstName'] = $userDetails['firstName'];
$this->parameters['email'] = $userDetails['email'];
$this->parameters['surName'] = $userDetails['lastName'];
$this->parameters['tier'] = $userDetails['tier'];
$this->parameters['userProfileImage'] = $userDetails['userProfileImage'];
$this->parameters['userProfileImageUrl'] = !empty($userDetails['userProfileImage']) ? $this->ltsUtils->getUploadPath('profile_pic', '', $userDetails['userProfileImage']) : '';
$this->parameters['fullName'] = $userDetails['fullName'];
$this->parameters['companyName'] = $userDetails['companyTitle'];
$this->parameters['roles'] = $user->getRoles();
$this->parameters['isMainAdmin'] = $user->isMainAdmin();
$this->parameters['isSuperAdmin'] = $user->isSuperAdmin();
$this->parameters['companyId'] = $this->companyId = $userDetails['companyId'];
$this->parameters['encodeCompanyId'] = base64_encode($userDetails['companyId']);
$this->parameters['userPrivilegeRoles'] = $userDetails['userPrivilegeRoles'];
$this->parameters['userType'] = $userDetails['userType'];
$this->parameters['ltsLogo'] = 'data-point-new-logo.png';
$this->parameters['companyImageUrl'] = !empty($userDetails['companyImage']) ? $this->ltsUtils->getUploadPath('company_logo', $this->parameters['encodeCompanyId'], $userDetails['companyImage']) : '';
$this->parameters['planExpireDate'] = $userDetails['planExpireDate'];
$this->parameters['plan'] = $userDetails['plan'];
$this->parameters['refId'] = $userDetails['refId'];
$this->parameters['previlageRoles'] = !empty($userDetails['userPrivilegeRoles']) ? $this->ltsUtils->getUserRoles($userDetails['userPrivilegeRoles']) : [];
}
}
/**
* Set Time zone.
*/
public function setTimeZone()
{
date_default_timezone_set('UTC');
}
/**
* @param type $event
* @param type $user
*/
private function setTopNavLinks($event, $user)
{
$request = $event->getRequest();
$resArray = $this->topNavbar->getData($request, $user);
if ($resArray) {
$this->container->get('twig')->addGlobal('topnav_data', $resArray['topnavData']);
$this->container->get('twig')->addGlobal('pagetitle_data', $resArray['pageTitleBlock']);
}
}
private function setDemoTourData()
{
$this->container->get('twig')->addGlobal('demo_tour_data', $this->ltsUtils->getDemoTourArray());
}
/**
* This function is to set contact details in twig object.
*/
private function setTwigVariables()
{
$this->container->get('twig')->addGlobal('fr_contact', $this->parameters);
$this->container->get('twig')->addGlobal('ltApp', $this->parameters);
}
/**
* This function is to set contact details in twig object.
*/
private function setCompanyDetails()
{
$this->parameters['defaultDateFormat'] = 'd-m-Y h:i:a';
$this->parameters['defaultDate'] = 'd-m-Y';
$this->parameters['defaultTime'] = 'h:i:a';
$this->parameters['defaultSystemLang'] = 'en';
$this->parameters['defaultTimezone'] = 'UTC';
$companyDetails = $this->em->getRepository(Terminology::class)->getCompanyDetails($this->companyId);
$companyDetails['timezone'] = !empty($companyDetails['timezone']) ? $companyDetails['timezone'] : '';
$this->parameters['lang'] = $companyDetails && !empty($companyDetails['systemLanguage']) ? $companyDetails['systemLanguage'] : 'en';
$this->parameters['timezone'] = isset($companyDetails['timezone']) ? $companyDetails['timezone'] : '';
$this->parameters['userRefidPrefix'] = !empty($companyDetails['userRefidPrefix']) ? $companyDetails['userRefidPrefix'] : '';
$this->parameters['cardRefidPrefix'] = !empty($companyDetails['cardRefidPrefix']) ? $companyDetails['cardRefidPrefix'] : '';
$this->parameters['cardRefidStartsFrom'] = !empty($companyDetails['cardRefidStartsFrom']) ? $companyDetails['cardRefidStartsFrom'] : '1';
$this->parameters['dataTimeFormat'] = $this->ltsUtils->getDateTimeFormat(isset($companyDetails['datetimeFormat']) ? $companyDetails['datetimeFormat'] : null);
$this->parameters['dataFormat'] = $this->ltsUtils->getDateFormat(isset($companyDetails['dateFormat']) ? $companyDetails['dateFormat'] : null);
$this->parameters['timeFormat'] = $this->ltsUtils->getTimeFormat(isset($companyDetails['timeFormat']) ? $companyDetails['timeFormat'] : null);
$this->parameters['companyTerminology'] = $this->ltsUtils->getTerminologyDetails($this->companyId);
// company plans limit setting
$this->parameters['companySettings'] = $companyDetails;
// dateTime formats for twig pages
$companyDetails['allDateTimeFormat'] = $this->ltsUtils->getDateTimeFormat(isset($companyDetails['datetimeFormat']) ? $companyDetails['datetimeFormat'] : null);
$companyDetails['allDateFormat'] = $this->ltsUtils->getDateFormat(isset($companyDetails['dateFormat']) ? $companyDetails['dateFormat'] : null);
$companyDetails['allTimeFormat'] = $this->ltsUtils->getTimeFormat(isset($companyDetails['timeFormat']) ? $companyDetails['timeFormat'] : null);
// inviduvidal company limitation
$this->parameters['c1'] = $companyDetails && !empty($companyDetails['c1']) ? $companyDetails['c1'] : 0;
$this->container->get('twig')->addGlobal('company', $companyDetails);
}
/**
* This function is to save last active time for each login session.
*/
private function saveLastActiveTime($event)
{
$request = $event->getRequest();
$params['routeName'] = $request->get('_route');
$params['loginUserId'] = $this->get('userId');
$params['company_id'] = $this->get('companyId');
if (isset($params['loginUserId']) && $this->em->isOpen()) {
$this->em->getRepository(LoginSessions::class)->update($params);
}
}
/**
* @param type $event
*/
private function checkForPlanExpiry($event)
{
if (!empty($this->parameters['planExpireDate']) && !$this->parameters['isSuperAdmin']) {
if ($this->parameters['planExpireDate']->format('Y-m-d') <= date('Y-m-d') && 'free_trail' == $this->parameters['plan']) {
$request = $event->getRequest();
$requestedUrl = $request->getRequestUri();
// If public demo accounts after expiring only this url will be allowed.
$allowedURLs = ['/settings/accounts', '/settings/get-account-settings-data', '/settings/get-terminology-data', '/settings/logo_upload', '/settings/save-account-settings-data', '/settings/save-terminology-data'];
if (!in_array($requestedUrl, $allowedURLs)) {
$redirectUrl = $this->router->generate('account-settings');
$response = new RedirectResponse($redirectUrl);
$event->setResponse($response);
}
$this->parameters['account_status'] = 'in-active';
}
}
}
/**
* In this function, verify if the logged-in user has the necessary privileges to access the route (when entered directly in the browser).
*
* @param $user
*
* @return void
*/
private function checkUserPrevilage($user,$event)
{
$companyDetails=$this->em->getRepository(Terminology::class)->getCompanyDetails($this->companyId);
$request = $event->getRequest();
$path = $request->getRequestUri();
$prev = true;
if( $path == $this->router->generate('product_list')){
$prev = $user ? in_array('ROLE_PRODUCT_MANAGEMENT_ADMIN', $user->getRoles()) || in_array('ROLE_PRODUCT_MANAGEMENT_VIEW', $user->getRoles()) : false;
} else if($path == $this->router->generate('product_variant_list')){
$prev = $user ? in_array('ROLE_PRODUCT_VARIANT_MANAGEMENT_VIEW', $user->getRoles()) || in_array('ROLE_PRODUCT_VARIANT_MANAGEMENT_ADMIN', $user->getRoles()) : false;
} else if($path == $this->router->generate('customer_list')){
$prev = $user ? in_array('ROLE_CUSTOMER_MANAGEMENT_VIEW', $user->getRoles()) || in_array('ROLE_CUSTOMER_MANAGEMENT_ADMIN', $user->getRoles()) : false;
} else if($path == $this->router->generate('boards_list')){
$prev = $user ? in_array('ROLE_BOARD_SETTINGS_VIEW', $user->getRoles()) || in_array('ROLE_BOARD_SETTINGS_ADMIN', $user->getRoles()) : false;
} else if($path == $this->router->generate('stock_management_list')){
$prev = $user ? in_array('ROLE_ASSY_STOCK_MANAGEMENT_VIEW', $user->getRoles()) || in_array('ROLE_ASSY_STOCK_MANAGEMENT_ADMIN', $user->getRoles()) : false;
} else if($path == $this->router->generate('smt_stock_management_list')){
$prev = $user ? in_array('ROLE_SMT_STOCK_MANAGEMENT_VIEW', $user->getRoles()) || in_array('ROLE_SMT_STOCK_MANAGEMENT_ADMIN', $user->getRoles()) : false;
} else if($path == $this->router->generate('running_order_view')){
$prev = $user ? in_array('ROLE_RUNNING_ORDER_VIEW', $user->getRoles()) || in_array('ROLE_RUNNING_ORDER_ADMIN', $user->getRoles()) : false;
} else if($path == $this->router->generate('master_production_schedule')){
$prev = $user ? in_array('ROLE_MASTER_PRODUCTION_SCHEDLE_REPORT_VIEW', $user->getRoles()) || in_array('ROLE_MASTER_PRODUCTION_SCHEDLE_REPORT_ADMIN', $user->getRoles()) : false;
} else if($path == $this->router->generate('activity_log')){
$prev = $user ? in_array('ROLE_ACTIVITY_LOG_VIEW', $user->getRoles()) || in_array('ROLE_ACTIVITY_LOG_ADMIN', $user->getRoles()) : false;
} else if($path == $this->router->generate('shift_assign')){
$prev = $user ? in_array('ROLE_MANAGE_SHIFT_VIEW', $user->getRoles()) || in_array('ROLE_MANAGE_SHIFT_ADMIN', $user->getRoles()) : false;
} else if($path == $this->router->generate('oee_list')){
$prev = $user ? in_array('ROLE_OEE_DAILY_TARGET_VIEW', $user->getRoles()) || in_array('ROLE_OEE_DAILY_TARGET_ADMIN', $user->getRoles()) : false;
} else if( $path == ($this->router->generate('user'))){
$prev = $user ? in_array('ROLE_USER_MANAGEMENT_VIEW', $user->getRoles()) || in_array('ROLE_USER_MANAGEMENT_ADMIN', $user->getRoles()) : false;
} else if($path == $this->router->generate('user_type')){
$prev = $user ? in_array('ROLE_USER_PRIVILEGE_VIEW', $user->getRoles()) || in_array('ROLE_USER_PRIVILEGE_ADMIN', $user->getRoles()) : false;
} else if($path == $this->router->generate('line_manager')){
$prev = $user ? in_array('ROLE_DAILY_PLAN_VIEW', $user->getRoles()) || in_array('ROLE_DAILY_PLAN_ADMIN', $user->getRoles()) : false;
} else if($path == $this->router->generate('workorder_details_table')){
$prev = $user ? in_array('ROLE_WORKORDER_DETAILS_VIEW', $user->getRoles()) || in_array('ROLE_WORKORDER_DETAILS_ADMIN', $user->getRoles()) : false;
} else if($path == $this->router->generate('downtime_planing')){
$prev = $user ? in_array('ROLE_DOWNTIME_PLANNING_VIEW', $user->getRoles()) || in_array('ROLE_DOWNTIME_PLANNING_ADMIN', $user->getRoles()) : false;
} else if($path == $this->router->generate('excel_import_history')){
$prev = $user ? in_array('ROLE_IMPORT_HISTORY_VIEW', $user->getRoles()) || in_array('ROLE_IMPORT_HISTORY_ADMIN', $user->getRoles()) : false;
} else if($path == $this->router->generate('production_settings')){
$prev = $user ? in_array('ROLE_PRODUCTION_SETTINGS_VIEW', $user->getRoles()) || in_array('ROLE_PRODUCTION_SETTINGS_ADMIN', $user->getRoles()) : false;
}
if(!$prev){
$msg = $this->translator->trans('ACCESS_DENIED');
throw new AccessDeniedHttpException($msg);
}
}
}