<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Routing\Annotation\Route;
use App\AppUtils\AppGoogleClient as AGC;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Request;
use Doctrine\ORM\EntityManagerInterface;
use App\Entity\Customer;
use App\Entity\AppTOS;
use App\Entity\UserConsent;
use App\Entity\Notification;
use Psr\Log\LoggerInterface;
use App\AppUtils\Tools;
class IndexController extends AbstractController
{
private $requestStack;
private $session;
private $em;
private $request;
private $logger;
public function __construct(RequestStack $requestStack,EntityManagerInterface $entityManager, LoggerInterface $logger)
{
$this->requestStack = $requestStack;
$this->session = $this->requestStack->getSession();
$this->em = $entityManager;
$this->request = Request::createFromGlobals();
$this->logger = $logger;
}
/**
* @Route("/demoindex", name="demoindex")
*/
public function demoindex(): Response
{
$autenticato = $this->isGranted('ROLE_USER'); //controlla se l'utente è autenticato
if ($autenticato){
//se l'utente è autenticato, lo rimanda al normale indice dell'applicativo
return $this->index();
}
else {
//se non è autenticato l'utente, renderizza la pagina generica
$datiUtente=null;
}
//lettura della configurazione dal doctrine
/*$datiUtente=[
'nomeutente' => $nomeUtente,
'nomeutentecompleto' => $googleFullName,
];*/
//
return $this->render('index/demoindex.html.twig', [
//'listaOU' => $listaOU,
//'debugOutput' => $listaOU,
'datiUtente' => $datiUtente,
'copyrightYear' => date('Y'),
]);
}
/**
* Metodo per prelevare le notifiche in ajax
* @Route("/getNotifications", name="get_notifications")
*/
public function get_notifications($parametri=null)
{
$http_status_code = 200;
//$dPO = ['']; //definizione parametri obbligatori
$dPF = ['daLeggere','limit','offset','daCreated']; //definizione parametri facoltativi
//prelevo per comodità
$sqlIDC = $this->session->get('sqlIDC');
$googleUID = $this->session->get('googleId');
$email = $this->session->get('email');
if ($sqlIDC !== null && $googleUID !== null && $email !== null){}
else {
return new JsonResponse(['error' => "parametri obbligatori non presenti nella request"],400);
}
//RICERCA MEDIANTE GOOGLE USERID UNIVOCO, PER COMPATIBILITA INTRODUCO UN IF/ELSE
/*if ($googleUID != null && $googleUID != ""){ //nel caso il google UserID in sessione sia presente, ricerco
$consenso = $this->em->getRepository(UserConsent::class)->findOneBy(['googleId' => $googleUID]); //l'oggetto consenso prelevato ricercando per id univoco google
} else {}
if ($consenso != null){} else { //se non l'ho trovato cercando per googleUID, per retrocompatibilità, cerco per email
$consenso = $this->em->getRepository(UserConsent::class)->findOneBy(['email' => $email]); //l'oggetto consenso prelevato ricercando per email
}*/
if ($parametri !== null){}
else {
$parametri = $this->request->get('parametri');
}
$optParams = Tools::getParametriSenzaNulli( Tools::getParametri($parametri,$dPF,false) );
//
$notifiche = $this->em->getRepository(Notification::class)->findByGoogleId($googleUID,$optParams);
return new JsonResponse($notifiche,$http_status_code);
}
/**
* Metodo per impostare lo status di lettura di una notifica in ajax
* @Route("/setNotification", name="set_notification")
*/
public function set_notification($parametri=null)
{
$output=[];
$http_status_code = 200;
if ($parametri !== null){}
else {
$parametri = $this->request->get('parametri');
}
//prelevo per comodità
$sqlIDC = $this->session->get('sqlIDC');
$googleUID = $this->session->get('googleId');
$email = $this->session->get('email');
$dPO = ['idnotifica','lettura']; //definizione parametri obbligatori
$parametriObbligatori = Tools::getParametri($parametri,$dPO);
if ($sqlIDC !== null && $googleUID !== null && $email !== null && $parametriObbligatori !== false){}
else {
$http_status_code = 400;
return new JsonResponse(["error"=>"mancano parametri obbligatori nella request"],$http_status_code);
}
//
$idnotifica = $parametriObbligatori['idnotifica'];
//$notifica = $this->em->getRepository(Notification::class)->find($idnotifica);
$optParams = [
'idnotifica' => $idnotifica
];
$notifiche = $this->em->getRepository(Notification::class)->findByGoogleId($googleUID,$optParams);
if ($notifiche !== null){
$notifica = $notifiche[0]; //array dettagli notifica
$n_obj = $this->em->getRepository(Notification::class)->find($idnotifica);
}
else {
$http_status_code = 404;
return new JsonResponse(["error"=>"notifica non rintracciata"],$http_status_code);
}
//valuto l'operazione richiesta, nel caso in cui la notifica abbia già lo status proposto, non effettuo alcuna operazione
if ( ( $parametri['lettura'] == 1 && $notifica['n_u_c_id'] !== null ) || ( $parametri['lettura'] == 0 && $notifica['n_u_c_id'] === null ) ){
//in questo caso non faccio modifiche
$output['cambio status'] = "non necessario status da impostare:{$parametri['lettura']}";
}
else {
//caso in cui debbo effettuare un cambio status, cerco il record consenso
$consenso = $this->em->getRepository(UserConsent::class)->find($notifica['u_c_id']); //l'oggetto consenso prelevato direttamente via id
if ($consenso !== null){}
else {
$http_status_code = 404;
return new JsonResponse(["error"=>"user_consent id:{$notifica['n_u_c_id']} non rintracciato"],$http_status_code);
}
if ($parametri['lettura'] == 1 ){ //se devo impostare la notifica come letta, dovrò creare uno user consent
$consenso->addNotification($n_obj); //aggiungo la notifica a quelle associate a tale userconsent
} else {//se devo impostare la notifica come già letta, elimino l'associazione con lo user consent
$consenso->removeNotification($n_obj); //aggiungo la notifica a quelle associate a tale userconsent
}
$output['cambio status'] = "necessario status da impostare:{$parametri['lettura']}";
$this->em->flush(); //propago le modifiche a database
}
//
return new JsonResponse(["notifica"=>$notifica],$http_status_code);
}
/**
* @Route("/index", name="index")
*/
public function index(): Response
{
//### Lettura dell'id customer dalla sessione
$sqlIDC = $this->session->get('sqlIDC');
$email = $this->session->get('email');
$nomeUtente=$this->session->get('nomeutente');
$googleFullName = $this->session->get('googleFullName');
$googleUID = $this->session->get('googleId');
//lettura della configurazione dal doctrine
$customer = $this->em->getRepository(Customer::class)->find($sqlIDC);
$gCustomerId = $customer->getGCustomerId();
$codMec = $customer->getCodMec();
$datiUtente=[
'nomeutente' => $nomeUtente,
'nomeutentecompleto' => $googleFullName,
];
//### Quando l'utente arriva all'index, è già autenticato con Google e ha già creato il token, qui devo semplicemente verificare
//### 1) Accettazione dei termini di servizio
$tos = $this->em->getRepository(AppTOS::class)->findOneBy(['idCustomer' => $sqlIDC]); //l'oggetto termini di servizio
//RICERCA MEDIANTE GOOGLE USERID UNIVOCO, PER COMPATIBILITA INTRODUCO UN IF/ELSE
$consenso = null; //fallback in caso non vada a buon fine nulla
if ($googleUID !== null && $googleUID != ""){ //nel caso il google UserID in sessione sia presente, ricerco
$consenso = $this->em->getRepository(UserConsent::class)->findOneBy(['googleId' => $googleUID]); //l'oggetto consenso prelevato ricercando per id univoco google
} else {}
if ($consenso !== null){} else { //se non l'ho trovato cercando per googleUID, per retrocompatibilità, cerco per email
$consenso = $this->em->getRepository(UserConsent::class)->findOneBy(['email' => $email]); //l'oggetto consenso prelevato ricercando per email
}
// verifico se il google id nel record consent è da aggiornare
if ($consenso !== null && ($consenso->getGoogleId() !== $googleUID) ){
try {
$consenso->setGoogleId($googleUID);
$this->em->flush(); //aggiorna il record
} catch(\Exception $ex){
//nel caso in cui non vada a buon fine l'update del googleUID
$report_debug = [
'email' => $email,
'googleUID' => $googleUID,
'userConsentId' => $consenso->getId(),
'ex_message' => $ex->getMessage(),
];
$this->logger->error("R90 eccezione consenso", $report_debug);
}
} else {}
//
if ($consenso && $consenso->getConsent()){ //se il consenso esiste e vale boolean true
//introduce la verifica temporale della durata del consenso
$dtConsent=$consenso->getDateTime(); //datetime salvato
$dtNow = new \DateTime("now"); //datetime attuale
$interval = $dtConsent->diff($dtNow); //intervallo temporale tra il presente e il momento del consenso
$anni = intval($interval->format('%y')); //intero che rappresenta gli anni trascorsi dal consenso
//$this->session->set('dtconsentdb',$dtConsent); //DEBUG
//$this->session->set('dtconsentnow',$dtNow); //DEBUG
//$this->session->set('intervalloConsent',$interval); //DEBUG
//$this->session->set('anni',$anni); //DEBUG
if ($anni >=2){ //quando gli anni passati dalla registrazione del consenso sono 2 o più, chiedo nuovamente la registrazione del consenso
if ($tos == null){
$tosDaTrasmettere = null;
} else {
$tosDaTrasmettere = $tos->getContent();
}
return $this->render('app-consent.html.twig',array(
//'titoloBrand'=>$customer->getGDomain(),'datiUtente'=>$datiUtente,'customerName'=>$customer->getName(),'terminidiutilizzo'=>$customer->getTOS(), 'anni' => $anni,
//'titoloBrand'=>$customer->getGDomain(),
'datiUtente'=>$datiUtente,'customerName'=>$customer->getName(),'terminidiutilizzo'=>$tosDaTrasmettere, 'anni' => $anni,
));
}
elseif ( ($tos!=null) && ($dtConsent < $tos->getLastUpdate() ) ){
$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
return $this->render('app-consent.html.twig',array(
//'titoloBrand'=>$customer->getGDomain(),
'datiUtente'=>$datiUtente,'customerName'=>$customer->getName(),'terminidiutilizzo'=>$tos->getContent(), 'anni' => $anni,
));
}
else {
//non fa niente
}
}
else {
//se il consenso non esiste, va alla schermata di richiesta
if ($tos == null){
$tosDaTrasmettere = null;
}
else {
$tosDaTrasmettere = $tos->getContent();
}
return $this->render('app-consent.html.twig',array(
//'titoloBrand'=>$customer->getGDomain(),'datiUtente'=>$datiUtente,'customerName'=>$customer->getName(),'terminidiutilizzo'=>$customer->getTOS(),
//'titoloBrand'=>$customer->getGDomain(),
'datiUtente'=>$datiUtente,'customerName'=>$customer->getName(),'terminidiutilizzo'=>$tosDaTrasmettere,
));
}
//### 2) Presenza dei parametri di configurazione necessari per far funzionare l'applicativo (di base l'OUBasePath)
$config = $customer->getConfig();
$gruppo_gsuite_operatori = $customer->getGruppoGsuiteOperatori();
$gruppo_gsuite_amministratori = $customer->getGruppoGsuiteAmministratori();
$AGC = new AGC($this->em,$codMec,$gCustomerId);
$AGC->startService();
//se uno dei parametri necessari manca o è nullo, richiedo la configurazione
if ($config == null || $config['ouBasePath']==null || $config['ouBasePath']=='' || $gruppo_gsuite_operatori==null || $gruppo_gsuite_operatori=='' || $gruppo_gsuite_amministratori==null || $gruppo_gsuite_amministratori=='' ){
$listaOU = $AGC->getAppOURootTree();
//fuoriesco le cose per la prima configurazione
return $this->render('index/index.html.twig', [
//'controller_name' => 'IndexController',
'primaconfigurazione' => [
'stepAttivazione' => 1,
'listaOU' => $listaOU,
],
'debugOutput' => '',//$listaOU,
'datiUtente' => $datiUtente
]);
}
else {
//
}
//controllo se è attivo anche il modulo di conservazione
if ( isset($config['conservazione']) && $config['conservazione'] == 'true'){
$this->session->set('conservazione','true');
}
else {}
//
//### Controllo se l'applicativo è in modalità di sola consultazione
if ($customer->getConsultationOnly() == 1){
return $this->render('index/index.html.twig', [
'datiUtente' => $datiUtente,
'solaConsultazione' => true,
]);
} else {} //proseguo senza fare altro
//### FINE Controllo se l'applicativo è in modalità di sola consultazione
return $this->render('index/index.html.twig', [
'datiUtente' => $datiUtente
]);
}
/**
* @Route("/indexAuth", name="indexAuth")
*/
public function indexAuth(): Response
{
return $this->render('index/index.html.twig', [
'controller_name' => 'IndexController',
]);
}
/**
* @Route("/logout", name="logout")
*/
public function logout($istituto="")
{
//nel caso in cui per il logout si arrivi da una pagina di logout di google
if ( isset($_SERVER['HTTP_REFERER']) && (strpos($_SERVER['HTTP_REFERER'], 'google') !== false)/* && (strpos($_SERVER['HTTP_REFERER'], 'logout') !== false)*/ ) {
return $this->render('app-logout.html.twig',array('titoloBrand'=>$istituto,'gsuitelogout'=>'true'));
}
// nel caso in cui invece il logout google non sia stato fatto
return $this->render('app-logout.html.twig',array('titoloBrand'=>$istituto));
}
/**
* metodo per salvare il consenso al trattamento dati
* @Route("/tos-consent", name="tos-consent")
*/
public function consent($istituto="", $datiUtente=null)
{
$appConsent = $this->request->get('appConsent'); //carica il valore del consenso
$email = $this->session->get('email');
$sqlIDC = $this->session->get('sqlIDC');
$googleId = $this->session->get('googleId');
$em = $this->getDoctrine()->getManager(); //carica il doctrine per verificare se esiste già il consenso
$consenso = $this->em->getRepository(UserConsent::class)->findOneBy(['email' => $email]); //l'oggetto consenso
$customer = $this->em->getRepository(Customer::class)->find($sqlIDC); //l'oggetto customer
$tos = $this->em->getRepository(AppTOS::class)->findOneBy(['idCustomer' => $sqlIDC]); //l'oggetto termini di servizio
$nomeUtente=$this->session->get('nomeutente');
$googleFullName = $this->session->get('googleFullName');
$datiUtente=[
'nomeutente' => $nomeUtente,
'nomeutentecompleto' => $googleFullName,
];
if ($tos == null){
//nel caso non siano stati inseriti termini di servizio custom, inserire un generico
$tos = new AppTOS();
$tos->setContent("Inserire Termini di Servizio Generici");
} else {}
if ($appConsent=="on"){
//il consenso è ok e procedo
}
else {
//rimanda nuovamente ai termini di servizio
if (isset($consenso)){
$consentId = $consenso->getId();
}
else {
$consentId = null;
}
//$aTOS = new AppTOSType();
//$form = $this->createForm(AppTOSType::class,$aTOS);
return $this->render('app-consent.html.twig',array(
//'titoloBrand'=>$customer->getGDomain(),'datiUtente'=>$datiUtente,'customerName'=>$customer->getName(),'terminidiutilizzo'=>$customer->getTOS(), 'idConsenso' => $consentId, /*'form' => $form->createView(),*/
//'titoloBrand'=>$customer->getGDomain(),
'datiUtente'=>$datiUtente,'customerName'=>$customer->getName(),'terminidiutilizzo'=>$tos->getContent(), 'idConsenso' => $consentId, /*'form' => $form->createView(),*/
));
}
if ($consenso){ //se il consenso esiste già
$consenso->setConsent(true); //aggiorno il valore del consenso
$datatempo = new \DateTime("now"); //datetime attuale
$consenso->setDatetime($datatempo); //aggiorno il datetime alla data attuale
$this->em->flush(); //eseguo eventuali aggiornamenti sospesi
}
else { //se il consenso non esiste già
$datatempo = new \DateTime("now"); //datetime attuale
$consenso = new UserConsent($email, $datatempo, $sqlIDC, $googleId); //creo una nuova istanza consenso
$this->em->persist($consenso); //salvo il nuovo oggetto
$this->em->flush(); //eseguo la query
}
$response = new Response();
$response->setContent('
<!DOCTYPE html>
<html>
<head>
<!-- HTML meta refresh URL redirection -->
<meta http-equiv="refresh"
content="0; url=/">
<style>body {
text-align: center;
}</style>
</head>
<body>
<p>Autenticato con Successo:
<a href="/">Torna alla Home</a></p>
</body>
</html>
');
$response->setStatusCode(Response::HTTP_OK);
$response->headers->set('Content-Type', 'text/html');
return $response;
}
/**
* metodo per salvare il consenso al trattamento dati
* @Route("/tos-destroy", name="tos-destroy")
*/
public function consentDestroy($istituto="", $datiUtente=null)
{
$appConsentDestroy = $this->request->get('appConsentDestroy'); //carica il valore del consenso
$consentId = $this->request->get('consentId'); //carica l'id del consenso da rimuovere
$email = $this->session->get('email');
$sqlIDC = $this->session->get('sqlIDC');
$consenso = $this->em->getRepository(UserConsent::class)->find($consentId); //carica l'oggetto consenso esistente
$customer = $this->em->getRepository(Customer::class)->find($sqlIDC); //carica l'oggetto customer (serve solo per render)
$tos = $this->em->getRepository(AppTOS::class)->findOneBy(['idCustomer' => $sqlIDC]); //l'oggetto termini di servizio
$nomeUtente=$this->session->get('nomeutente');
$googleFullName = $this->session->get('googleFullName');
$datiUtente=[
'nomeutente' => $nomeUtente,
'nomeutentecompleto' => $googleFullName,
];
if ($tos == null){
//nel caso non siano stati inseriti termini di servizio custom, inserire un generico
$tos = new AppTOS();
$tos->setContent("Inserire Termini di Servizio Generici");
} else {}
if ($appConsentDestroy=="on"){
//distruggo il consenso
$this->em->remove($consenso);
$this->em->flush();
}
else {
// non fa niente
}
//se era presente, il consenso è distrutto e procedo a richiederlo nuovamente
return $this->render('app-consent.html.twig',array(
//'titoloBrand'=>$customer->getGDomain(),'datiUtente'=>$datiUtente,'customerName'=>$customer->getName(),'terminidiutilizzo'=>$customer->getTOS(), 'consensorimosso' => true,
//'titoloBrand'=>$customer->getGDomain(),
'datiUtente'=>$datiUtente,'customerName'=>$customer->getName(),'terminidiutilizzo'=>$tos->getContent(), 'consensorimosso' => true,
));
}
/**
* metodo per il keep alive di sessione
* @Route("/ajax/appSessionPing", name="appSessionPing")
*/
public function appSessionPing()
{
$session = $this->container->get('session'); //importa la sessione
$sqlIDC = $session->get('sqlIDC'); //controlla l'id sql customer
if ($sqlIDC == null){
$sessionping = true;
$htmlStatusCode = 200;
}
else {
$sessionping = false;
$htmlStatusCode = 401;
}
$response= array(
//"error" => true,
"code" => $htmlStatusCode,
"response" => $sessionping,
);
return new JsonResponse($response);
}
/**
* metodo per i termini e condizione generali, da non autenticato
* @Route("/tos-public", name="tospublic")
*/
public function tospublic(){
return $this->render(
'app-consent.html.twig',
[
'route_name' => 'tospublic'
]
);
}
//### FINE CONTROLLER
}