src/Controller/IndexController.php line 40

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  4. use Symfony\Component\HttpFoundation\Response;
  5. use Symfony\Component\HttpFoundation\JsonResponse;
  6. use Symfony\Component\Routing\Annotation\Route;
  7. use App\AppUtils\AppGoogleClient as AGC;
  8. use Symfony\Component\HttpFoundation\RequestStack;
  9. use Symfony\Component\HttpFoundation\Request;
  10. use Doctrine\ORM\EntityManagerInterface;
  11. use App\Entity\Customer;
  12. use App\Entity\AppTOS;
  13. use App\Entity\UserConsent;
  14. use App\Entity\Notification;
  15. use Psr\Log\LoggerInterface;
  16. use App\AppUtils\Tools;
  17. class IndexController extends AbstractController
  18. {
  19. private $requestStack;
  20. private $session;
  21. private $em;
  22. private $request;
  23. private $logger;
  24. public function __construct(RequestStack $requestStack,EntityManagerInterface $entityManager, LoggerInterface $logger)
  25. {
  26. $this->requestStack = $requestStack;
  27. $this->session = $this->requestStack->getSession();
  28. $this->em = $entityManager;
  29. $this->request = Request::createFromGlobals();
  30. $this->logger = $logger;
  31. }
  32. /**
  33. * @Route("/demoindex", name="demoindex")
  34. */
  35. public function demoindex(): Response
  36. {
  37. $autenticato = $this->isGranted('ROLE_USER'); //controlla se l'utente è autenticato
  38. if ($autenticato){
  39. //se l'utente è autenticato, lo rimanda al normale indice dell'applicativo
  40. return $this->index();
  41. }
  42. else {
  43. //se non è autenticato l'utente, renderizza la pagina generica
  44. $datiUtente=null;
  45. }
  46. //lettura della configurazione dal doctrine
  47. /*$datiUtente=[
  48. 'nomeutente' => $nomeUtente,
  49. 'nomeutentecompleto' => $googleFullName,
  50. ];*/
  51. //
  52. return $this->render('index/demoindex.html.twig', [
  53. //'listaOU' => $listaOU,
  54. //'debugOutput' => $listaOU,
  55. 'datiUtente' => $datiUtente,
  56. 'copyrightYear' => date('Y'),
  57. ]);
  58. }
  59. /**
  60. * Metodo per prelevare le notifiche in ajax
  61. * @Route("/getNotifications", name="get_notifications")
  62. */
  63. public function get_notifications($parametri=null)
  64. {
  65. $http_status_code = 200;
  66. //$dPO = ['']; //definizione parametri obbligatori
  67. $dPF = ['daLeggere','limit','offset','daCreated']; //definizione parametri facoltativi
  68. //prelevo per comodità
  69. $sqlIDC = $this->session->get('sqlIDC');
  70. $googleUID = $this->session->get('googleId');
  71. $email = $this->session->get('email');
  72. if ($sqlIDC !== null && $googleUID !== null && $email !== null){}
  73. else {
  74. return new JsonResponse(['error' => "parametri obbligatori non presenti nella request"],400);
  75. }
  76. //RICERCA MEDIANTE GOOGLE USERID UNIVOCO, PER COMPATIBILITA INTRODUCO UN IF/ELSE
  77. /*if ($googleUID != null && $googleUID != ""){ //nel caso il google UserID in sessione sia presente, ricerco
  78. $consenso = $this->em->getRepository(UserConsent::class)->findOneBy(['googleId' => $googleUID]); //l'oggetto consenso prelevato ricercando per id univoco google
  79. } else {}
  80. if ($consenso != null){} else { //se non l'ho trovato cercando per googleUID, per retrocompatibilità, cerco per email
  81. $consenso = $this->em->getRepository(UserConsent::class)->findOneBy(['email' => $email]); //l'oggetto consenso prelevato ricercando per email
  82. }*/
  83. if ($parametri !== null){}
  84. else {
  85. $parametri = $this->request->get('parametri');
  86. }
  87. $optParams = Tools::getParametriSenzaNulli( Tools::getParametri($parametri,$dPF,false) );
  88. //
  89. $notifiche = $this->em->getRepository(Notification::class)->findByGoogleId($googleUID,$optParams);
  90. return new JsonResponse($notifiche,$http_status_code);
  91. }
  92. /**
  93. * Metodo per impostare lo status di lettura di una notifica in ajax
  94. * @Route("/setNotification", name="set_notification")
  95. */
  96. public function set_notification($parametri=null)
  97. {
  98. $output=[];
  99. $http_status_code = 200;
  100. if ($parametri !== null){}
  101. else {
  102. $parametri = $this->request->get('parametri');
  103. }
  104. //prelevo per comodità
  105. $sqlIDC = $this->session->get('sqlIDC');
  106. $googleUID = $this->session->get('googleId');
  107. $email = $this->session->get('email');
  108. $dPO = ['idnotifica','lettura']; //definizione parametri obbligatori
  109. $parametriObbligatori = Tools::getParametri($parametri,$dPO);
  110. if ($sqlIDC !== null && $googleUID !== null && $email !== null && $parametriObbligatori !== false){}
  111. else {
  112. $http_status_code = 400;
  113. return new JsonResponse(["error"=>"mancano parametri obbligatori nella request"],$http_status_code);
  114. }
  115. //
  116. $idnotifica = $parametriObbligatori['idnotifica'];
  117. //$notifica = $this->em->getRepository(Notification::class)->find($idnotifica);
  118. $optParams = [
  119. 'idnotifica' => $idnotifica
  120. ];
  121. $notifiche = $this->em->getRepository(Notification::class)->findByGoogleId($googleUID,$optParams);
  122. if ($notifiche !== null){
  123. $notifica = $notifiche[0]; //array dettagli notifica
  124. $n_obj = $this->em->getRepository(Notification::class)->find($idnotifica);
  125. }
  126. else {
  127. $http_status_code = 404;
  128. return new JsonResponse(["error"=>"notifica non rintracciata"],$http_status_code);
  129. }
  130. //valuto l'operazione richiesta, nel caso in cui la notifica abbia già lo status proposto, non effettuo alcuna operazione
  131. if ( ( $parametri['lettura'] == 1 && $notifica['n_u_c_id'] !== null ) || ( $parametri['lettura'] == 0 && $notifica['n_u_c_id'] === null ) ){
  132. //in questo caso non faccio modifiche
  133. $output['cambio status'] = "non necessario status da impostare:{$parametri['lettura']}";
  134. }
  135. else {
  136. //caso in cui debbo effettuare un cambio status, cerco il record consenso
  137. $consenso = $this->em->getRepository(UserConsent::class)->find($notifica['u_c_id']); //l'oggetto consenso prelevato direttamente via id
  138. if ($consenso !== null){}
  139. else {
  140. $http_status_code = 404;
  141. return new JsonResponse(["error"=>"user_consent id:{$notifica['n_u_c_id']} non rintracciato"],$http_status_code);
  142. }
  143. if ($parametri['lettura'] == 1 ){ //se devo impostare la notifica come letta, dovrò creare uno user consent
  144. $consenso->addNotification($n_obj); //aggiungo la notifica a quelle associate a tale userconsent
  145. } else {//se devo impostare la notifica come già letta, elimino l'associazione con lo user consent
  146. $consenso->removeNotification($n_obj); //aggiungo la notifica a quelle associate a tale userconsent
  147. }
  148. $output['cambio status'] = "necessario status da impostare:{$parametri['lettura']}";
  149. $this->em->flush(); //propago le modifiche a database
  150. }
  151. //
  152. return new JsonResponse(["notifica"=>$notifica],$http_status_code);
  153. }
  154. /**
  155. * @Route("/index", name="index")
  156. */
  157. public function index(): Response
  158. {
  159. //### Lettura dell'id customer dalla sessione
  160. $sqlIDC = $this->session->get('sqlIDC');
  161. $email = $this->session->get('email');
  162. $nomeUtente=$this->session->get('nomeutente');
  163. $googleFullName = $this->session->get('googleFullName');
  164. $googleUID = $this->session->get('googleId');
  165. //lettura della configurazione dal doctrine
  166. $customer = $this->em->getRepository(Customer::class)->find($sqlIDC);
  167. $gCustomerId = $customer->getGCustomerId();
  168. $codMec = $customer->getCodMec();
  169. $datiUtente=[
  170. 'nomeutente' => $nomeUtente,
  171. 'nomeutentecompleto' => $googleFullName,
  172. ];
  173. //### Quando l'utente arriva all'index, è già autenticato con Google e ha già creato il token, qui devo semplicemente verificare
  174. //### 1) Accettazione dei termini di servizio
  175. $tos = $this->em->getRepository(AppTOS::class)->findOneBy(['idCustomer' => $sqlIDC]); //l'oggetto termini di servizio
  176. //RICERCA MEDIANTE GOOGLE USERID UNIVOCO, PER COMPATIBILITA INTRODUCO UN IF/ELSE
  177. $consenso = null; //fallback in caso non vada a buon fine nulla
  178. if ($googleUID !== null && $googleUID != ""){ //nel caso il google UserID in sessione sia presente, ricerco
  179. $consenso = $this->em->getRepository(UserConsent::class)->findOneBy(['googleId' => $googleUID]); //l'oggetto consenso prelevato ricercando per id univoco google
  180. } else {}
  181. if ($consenso !== null){} else { //se non l'ho trovato cercando per googleUID, per retrocompatibilità, cerco per email
  182. $consenso = $this->em->getRepository(UserConsent::class)->findOneBy(['email' => $email]); //l'oggetto consenso prelevato ricercando per email
  183. }
  184. // verifico se il google id nel record consent è da aggiornare
  185. if ($consenso !== null && ($consenso->getGoogleId() !== $googleUID) ){
  186. try {
  187. $consenso->setGoogleId($googleUID);
  188. $this->em->flush(); //aggiorna il record
  189. } catch(\Exception $ex){
  190. //nel caso in cui non vada a buon fine l'update del googleUID
  191. $report_debug = [
  192. 'email' => $email,
  193. 'googleUID' => $googleUID,
  194. 'userConsentId' => $consenso->getId(),
  195. 'ex_message' => $ex->getMessage(),
  196. ];
  197. $this->logger->error("R90 eccezione consenso", $report_debug);
  198. }
  199. } else {}
  200. //
  201. if ($consenso && $consenso->getConsent()){ //se il consenso esiste e vale boolean true
  202. //introduce la verifica temporale della durata del consenso
  203. $dtConsent=$consenso->getDateTime(); //datetime salvato
  204. $dtNow = new \DateTime("now"); //datetime attuale
  205. $interval = $dtConsent->diff($dtNow); //intervallo temporale tra il presente e il momento del consenso
  206. $anni = intval($interval->format('%y')); //intero che rappresenta gli anni trascorsi dal consenso
  207. //$this->session->set('dtconsentdb',$dtConsent); //DEBUG
  208. //$this->session->set('dtconsentnow',$dtNow); //DEBUG
  209. //$this->session->set('intervalloConsent',$interval); //DEBUG
  210. //$this->session->set('anni',$anni); //DEBUG
  211. if ($anni >=2){ //quando gli anni passati dalla registrazione del consenso sono 2 o più, chiedo nuovamente la registrazione del consenso
  212. if ($tos == null){
  213. $tosDaTrasmettere = null;
  214. } else {
  215. $tosDaTrasmettere = $tos->getContent();
  216. }
  217. return $this->render('app-consent.html.twig',array(
  218. //'titoloBrand'=>$customer->getGDomain(),'datiUtente'=>$datiUtente,'customerName'=>$customer->getName(),'terminidiutilizzo'=>$customer->getTOS(), 'anni' => $anni,
  219. //'titoloBrand'=>$customer->getGDomain(),
  220. 'datiUtente'=>$datiUtente,'customerName'=>$customer->getName(),'terminidiutilizzo'=>$tosDaTrasmettere, 'anni' => $anni,
  221. ));
  222. }
  223. elseif ( ($tos!=null) && ($dtConsent < $tos->getLastUpdate() ) ){
  224. $anni = -1; //fissa a -1 in modo da far capire che sono stati cambiati i TOS in data più recente rispetto a quella del consenso
  225. return $this->render('app-consent.html.twig',array(
  226. //'titoloBrand'=>$customer->getGDomain(),
  227. 'datiUtente'=>$datiUtente,'customerName'=>$customer->getName(),'terminidiutilizzo'=>$tos->getContent(), 'anni' => $anni,
  228. ));
  229. }
  230. else {
  231. //non fa niente
  232. }
  233. }
  234. else {
  235. //se il consenso non esiste, va alla schermata di richiesta
  236. if ($tos == null){
  237. $tosDaTrasmettere = null;
  238. }
  239. else {
  240. $tosDaTrasmettere = $tos->getContent();
  241. }
  242. return $this->render('app-consent.html.twig',array(
  243. //'titoloBrand'=>$customer->getGDomain(),'datiUtente'=>$datiUtente,'customerName'=>$customer->getName(),'terminidiutilizzo'=>$customer->getTOS(),
  244. //'titoloBrand'=>$customer->getGDomain(),
  245. 'datiUtente'=>$datiUtente,'customerName'=>$customer->getName(),'terminidiutilizzo'=>$tosDaTrasmettere,
  246. ));
  247. }
  248. //### 2) Presenza dei parametri di configurazione necessari per far funzionare l'applicativo (di base l'OUBasePath)
  249. $config = $customer->getConfig();
  250. $gruppo_gsuite_operatori = $customer->getGruppoGsuiteOperatori();
  251. $gruppo_gsuite_amministratori = $customer->getGruppoGsuiteAmministratori();
  252. $AGC = new AGC($this->em,$codMec,$gCustomerId);
  253. $AGC->startService();
  254. //se uno dei parametri necessari manca o è nullo, richiedo la configurazione
  255. if ($config == null || $config['ouBasePath']==null || $config['ouBasePath']=='' || $gruppo_gsuite_operatori==null || $gruppo_gsuite_operatori=='' || $gruppo_gsuite_amministratori==null || $gruppo_gsuite_amministratori=='' ){
  256. $listaOU = $AGC->getAppOURootTree();
  257. //fuoriesco le cose per la prima configurazione
  258. return $this->render('index/index.html.twig', [
  259. //'controller_name' => 'IndexController',
  260. 'primaconfigurazione' => [
  261. 'stepAttivazione' => 1,
  262. 'listaOU' => $listaOU,
  263. ],
  264. 'debugOutput' => '',//$listaOU,
  265. 'datiUtente' => $datiUtente
  266. ]);
  267. }
  268. else {
  269. //
  270. }
  271. //controllo se è attivo anche il modulo di conservazione
  272. if ( isset($config['conservazione']) && $config['conservazione'] == 'true'){
  273. $this->session->set('conservazione','true');
  274. }
  275. else {}
  276. //
  277. //### Controllo se l'applicativo è in modalità di sola consultazione
  278. if ($customer->getConsultationOnly() == 1){
  279. return $this->render('index/index.html.twig', [
  280. 'datiUtente' => $datiUtente,
  281. 'solaConsultazione' => true,
  282. ]);
  283. } else {} //proseguo senza fare altro
  284. //### FINE Controllo se l'applicativo è in modalità di sola consultazione
  285. return $this->render('index/index.html.twig', [
  286. 'datiUtente' => $datiUtente
  287. ]);
  288. }
  289. /**
  290. * @Route("/indexAuth", name="indexAuth")
  291. */
  292. public function indexAuth(): Response
  293. {
  294. return $this->render('index/index.html.twig', [
  295. 'controller_name' => 'IndexController',
  296. ]);
  297. }
  298. /**
  299. * @Route("/logout", name="logout")
  300. */
  301. public function logout($istituto="")
  302. {
  303. //nel caso in cui per il logout si arrivi da una pagina di logout di google
  304. if ( isset($_SERVER['HTTP_REFERER']) && (strpos($_SERVER['HTTP_REFERER'], 'google') !== false)/* && (strpos($_SERVER['HTTP_REFERER'], 'logout') !== false)*/ ) {
  305. return $this->render('app-logout.html.twig',array('titoloBrand'=>$istituto,'gsuitelogout'=>'true'));
  306. }
  307. // nel caso in cui invece il logout google non sia stato fatto
  308. return $this->render('app-logout.html.twig',array('titoloBrand'=>$istituto));
  309. }
  310. /**
  311. * metodo per salvare il consenso al trattamento dati
  312. * @Route("/tos-consent", name="tos-consent")
  313. */
  314. public function consent($istituto="", $datiUtente=null)
  315. {
  316. $appConsent = $this->request->get('appConsent'); //carica il valore del consenso
  317. $email = $this->session->get('email');
  318. $sqlIDC = $this->session->get('sqlIDC');
  319. $googleId = $this->session->get('googleId');
  320. $em = $this->getDoctrine()->getManager(); //carica il doctrine per verificare se esiste già il consenso
  321. $consenso = $this->em->getRepository(UserConsent::class)->findOneBy(['email' => $email]); //l'oggetto consenso
  322. $customer = $this->em->getRepository(Customer::class)->find($sqlIDC); //l'oggetto customer
  323. $tos = $this->em->getRepository(AppTOS::class)->findOneBy(['idCustomer' => $sqlIDC]); //l'oggetto termini di servizio
  324. $nomeUtente=$this->session->get('nomeutente');
  325. $googleFullName = $this->session->get('googleFullName');
  326. $datiUtente=[
  327. 'nomeutente' => $nomeUtente,
  328. 'nomeutentecompleto' => $googleFullName,
  329. ];
  330. if ($tos == null){
  331. //nel caso non siano stati inseriti termini di servizio custom, inserire un generico
  332. $tos = new AppTOS();
  333. $tos->setContent("Inserire Termini di Servizio Generici");
  334. } else {}
  335. if ($appConsent=="on"){
  336. //il consenso è ok e procedo
  337. }
  338. else {
  339. //rimanda nuovamente ai termini di servizio
  340. if (isset($consenso)){
  341. $consentId = $consenso->getId();
  342. }
  343. else {
  344. $consentId = null;
  345. }
  346. //$aTOS = new AppTOSType();
  347. //$form = $this->createForm(AppTOSType::class,$aTOS);
  348. return $this->render('app-consent.html.twig',array(
  349. //'titoloBrand'=>$customer->getGDomain(),'datiUtente'=>$datiUtente,'customerName'=>$customer->getName(),'terminidiutilizzo'=>$customer->getTOS(), 'idConsenso' => $consentId, /*'form' => $form->createView(),*/
  350. //'titoloBrand'=>$customer->getGDomain(),
  351. 'datiUtente'=>$datiUtente,'customerName'=>$customer->getName(),'terminidiutilizzo'=>$tos->getContent(), 'idConsenso' => $consentId, /*'form' => $form->createView(),*/
  352. ));
  353. }
  354. if ($consenso){ //se il consenso esiste già
  355. $consenso->setConsent(true); //aggiorno il valore del consenso
  356. $datatempo = new \DateTime("now"); //datetime attuale
  357. $consenso->setDatetime($datatempo); //aggiorno il datetime alla data attuale
  358. $this->em->flush(); //eseguo eventuali aggiornamenti sospesi
  359. }
  360. else { //se il consenso non esiste già
  361. $datatempo = new \DateTime("now"); //datetime attuale
  362. $consenso = new UserConsent($email, $datatempo, $sqlIDC, $googleId); //creo una nuova istanza consenso
  363. $this->em->persist($consenso); //salvo il nuovo oggetto
  364. $this->em->flush(); //eseguo la query
  365. }
  366. $response = new Response();
  367. $response->setContent('
  368. <!DOCTYPE html>
  369. <html>
  370. <head>
  371. <!-- HTML meta refresh URL redirection -->
  372. <meta http-equiv="refresh"
  373. content="0; url=/">
  374. <style>body {
  375. text-align: center;
  376. }</style>
  377. </head>
  378. <body>
  379. <p>Autenticato con Successo:
  380. <a href="/">Torna alla Home</a></p>
  381. </body>
  382. </html>
  383. ');
  384. $response->setStatusCode(Response::HTTP_OK);
  385. $response->headers->set('Content-Type', 'text/html');
  386. return $response;
  387. }
  388. /**
  389. * metodo per salvare il consenso al trattamento dati
  390. * @Route("/tos-destroy", name="tos-destroy")
  391. */
  392. public function consentDestroy($istituto="", $datiUtente=null)
  393. {
  394. $appConsentDestroy = $this->request->get('appConsentDestroy'); //carica il valore del consenso
  395. $consentId = $this->request->get('consentId'); //carica l'id del consenso da rimuovere
  396. $email = $this->session->get('email');
  397. $sqlIDC = $this->session->get('sqlIDC');
  398. $consenso = $this->em->getRepository(UserConsent::class)->find($consentId); //carica l'oggetto consenso esistente
  399. $customer = $this->em->getRepository(Customer::class)->find($sqlIDC); //carica l'oggetto customer (serve solo per render)
  400. $tos = $this->em->getRepository(AppTOS::class)->findOneBy(['idCustomer' => $sqlIDC]); //l'oggetto termini di servizio
  401. $nomeUtente=$this->session->get('nomeutente');
  402. $googleFullName = $this->session->get('googleFullName');
  403. $datiUtente=[
  404. 'nomeutente' => $nomeUtente,
  405. 'nomeutentecompleto' => $googleFullName,
  406. ];
  407. if ($tos == null){
  408. //nel caso non siano stati inseriti termini di servizio custom, inserire un generico
  409. $tos = new AppTOS();
  410. $tos->setContent("Inserire Termini di Servizio Generici");
  411. } else {}
  412. if ($appConsentDestroy=="on"){
  413. //distruggo il consenso
  414. $this->em->remove($consenso);
  415. $this->em->flush();
  416. }
  417. else {
  418. // non fa niente
  419. }
  420. //se era presente, il consenso è distrutto e procedo a richiederlo nuovamente
  421. return $this->render('app-consent.html.twig',array(
  422. //'titoloBrand'=>$customer->getGDomain(),'datiUtente'=>$datiUtente,'customerName'=>$customer->getName(),'terminidiutilizzo'=>$customer->getTOS(), 'consensorimosso' => true,
  423. //'titoloBrand'=>$customer->getGDomain(),
  424. 'datiUtente'=>$datiUtente,'customerName'=>$customer->getName(),'terminidiutilizzo'=>$tos->getContent(), 'consensorimosso' => true,
  425. ));
  426. }
  427. /**
  428. * metodo per il keep alive di sessione
  429. * @Route("/ajax/appSessionPing", name="appSessionPing")
  430. */
  431. public function appSessionPing()
  432. {
  433. $session = $this->container->get('session'); //importa la sessione
  434. $sqlIDC = $session->get('sqlIDC'); //controlla l'id sql customer
  435. if ($sqlIDC == null){
  436. $sessionping = true;
  437. $htmlStatusCode = 200;
  438. }
  439. else {
  440. $sessionping = false;
  441. $htmlStatusCode = 401;
  442. }
  443. $response= array(
  444. //"error" => true,
  445. "code" => $htmlStatusCode,
  446. "response" => $sessionping,
  447. );
  448. return new JsonResponse($response);
  449. }
  450. /**
  451. * metodo per i termini e condizione generali, da non autenticato
  452. * @Route("/tos-public", name="tospublic")
  453. */
  454. public function tospublic(){
  455. return $this->render(
  456. 'app-consent.html.twig',
  457. [
  458. 'route_name' => 'tospublic'
  459. ]
  460. );
  461. }
  462. //### FINE CONTROLLER
  463. }