<?php
namespace App\Controller;
use App\Entity\Agency;
use App\Entity\Address;
use App\Entity\JoinTableAgencyUser;
use App\Entity\User;
use App\Entity\UserDetail;
use App\Form\AgencyRegistrationType;
use App\Form\PasswordCreationType;
use App\Form\PasswordRecoveryType;
use App\Service\ValidationService;
use Doctrine\Persistence\ManagerRegistry;
use Symfony\Bridge\Twig\Mime\TemplatedEmail;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Symfony\Component\Form\FormError;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
use Symfony\Contracts\Translation\TranslatorInterface;
use Symfony\Component\Validator\Validator\ValidatorInterface;
/**
* @Route({"en": "/en", "it": "/it"}, defaults={"_locale" = "it"}, requirements={"_locale" = "it|en"})
*/
class SecurityController extends AbstractController
{
protected $mr;
private $params;
public function __construct(ManagerRegistry $managerRegistry, ParameterBagInterface $params)
{
$this->mr = $managerRegistry;
$this->params = $params;
}
/**
* @Route({"en":"/", "it":"/"}, name="homepage")
*/
public function homepage(Request $request, MailerInterface $mailer, AuthenticationUtils $authenticationUtils, TranslatorInterface $translator): Response
{
$em = $this->mr->getManager();
$session = $request->getSession();
$error = $authenticationUtils->getLastAuthenticationError();
$lastUsername = $authenticationUtils->getLastUsername();
$pswUser = new User();
$form = $this->createForm(PasswordRecoveryType::class, $pswUser, array('locale' => $request->getLocale()));
$form->handleRequest($request);
if($form->isSubmitted()){
$valid = true;
$path = 'https://www.google.com/recaptcha/api/siteverify?secret=6LcEdHAnAAAAAGDMfuV9qKR-EzPOBx7N24Liqjin&response='.$request->request->get("g-recaptcha-response");
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Accept: application/json')
);
curl_setopt($ch, CURLOPT_URL,$path);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
$result = curl_exec($ch);
curl_close($ch);
$res = json_decode($result, true);
if(!$res["success"]){
$valid = false;
$form->get('recaptcha')->addError(new FormError($translator->trans('flash_login_01', [], 'website')));
$this->addFlash('notice_warning', $translator->trans('flash_login_02', [], 'website'));
}
if($valid && $form->isValid()){
$user = $em->getRepository("App\Entity\User")->findOneByEmail($pswUser->getEmail());
if($user){
$user->setOneTimeCode(md5(uniqid()));
$em->flush();
$message = (new TemplatedEmail())
->subject($this->params->get('subject_recover_password'))
->from($this->params->get('sender_email'))
->to($user->getEmail())
->htmlTemplate('email/password_recovery.html.twig')
->context(['user' => $user]);
$mailer->send($message);
}
$this->addFlash('notice_success', $translator->trans('flash_login_03', [], 'website'));
return $this->redirectToRoute('homepage');
}
else
$this->addFlash('notice_warning', $translator->trans('flash_login_04', [], 'website'));
}
return $this->render('default/index.html.twig', array(
'last_username' => $lastUsername,
'error' => $error,
'form' => $form->createView()
));
}
/**
* @Route({"en":"/login-check", "it":"/accedi-controllo"}, name="login_check")
*/
public function loginCheck() {}
/**
* @Route({"en":"/logout", "it":"/disconnetti"}, name="logout")
*/
public function logout() {}
/**
* @Route({"en":"/registration", "it":"/registrati"}, name="registration")
*/
public function registration(Request $request, ValidatorInterface $validator, TranslatorInterface $translator, MailerInterface $mailer)
{
$em = $this->mr->getManager();
$session = $request->getSession();
$agency = new Agency();
$form = $this->createForm(AgencyRegistrationType::class, $agency);
$form->handleRequest($request);
if($form->isSubmitted()){
$valid = true;
if($valid) $valid = ValidationService::validateNotBlank($validator, $translator, $form->get('userName'));
if($valid) $valid = ValidationService::validateNotBlank($validator, $translator, $form->get('userSurname'));
if($valid) $valid = ValidationService::validateNotBlank($validator, $translator, $form->get('userEmail'));
if($valid) $valid = ValidationService::validateNotDuplicate($validator, $translator, $form->get('userEmail'), $em, "App\Entity\User", ['id' => -1]);
if($valid) $valid = ValidationService::validateNotDuplicate($validator, $translator, $form->get('vat'), $em, "App\Entity\Agency", ['id' => -1]);
if($valid) $valid = ValidationService::validateNotBlank($validator, $translator, $form->get('street'));
if($valid) $valid = ValidationService::validateNotBlank($validator, $translator, $form->get('number'));
if($valid) $valid = ValidationService::validateNotBlank($validator, $translator, $form->get('zip'));
if($valid) $valid = ValidationService::validateNotBlank($validator, $translator, $form->get('city'));
if($valid) $valid = ValidationService::validateNotBlank($validator, $translator, $form->get('province'));
$path = 'https://www.google.com/recaptcha/api/siteverify?secret=6LcEdHAnAAAAAGDMfuV9qKR-EzPOBx7N24Liqjin&response='.$request->request->get("g-recaptcha-response");
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Accept: application/json'));
curl_setopt($ch, CURLOPT_URL, $path);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
$result = curl_exec($ch);
curl_close($ch);
$res = json_decode($result, true);
if(!$res["success"]){
$valid = false;
$form->get('recaptcha')->addError(new FormError($translator->trans('flash_registration_01', [], 'website')));
$this->addFlash('notice_warning', $translator->trans('flash_registration_02', [], 'website'));
}
if($valid && $form->isValid()){
$agencyGroup = $em->getRepository('App\Entity\AgencyGroup')->findOneById(1); // Gruppo Holidays
$agency->setDirectoryPath(uniqid());
$agency->setGroup($agencyGroup);
$em->persist($agency);
$address = new Address();
$address->setAgency($agency);
$address->setName('Sede legale');
$address->setStreet($form->get('street')->getData());
$address->setNumber($form->get('number')->getData());
$address->setInternal($form->get('internal')->getData());
$address->setStairs($form->get('stairs')->getData());
$address->setFloor($form->get('floor')->getData());
$address->setZip($form->get('zip')->getData());
$address->setCity($form->get('city')->getData());
$address->setProvince($form->get('province')->getData());
$em->persist($address);
$user = new User();
$user->setEmail($form->get('userEmail')->getData());
$user->setName($form->get('userName')->getData());
$user->setSurname($form->get('userSurname')->getData());
$user->setRole('ROLE_USER');
$user->setDirectoryPath(uniqid());
$user->setOneTimeCode(md5(uniqid()));
$user->setAdminActive(true);
$em->persist($user);
$userDetail = new UserDetail();
$userDetail->setUser($user);
$em->persist($userDetail);
$jtau = new JoinTableAgencyUser();
$jtau->setAgency($agency);
$jtau->setUser($user);
$jtau->setActive(true);
$jtau->setAgencyAdmin(true);
$em->persist($jtau);
$em->flush();
$message = (new TemplatedEmail())
->subject($this->params->get('subject_registration'))
->from($this->params->get('sender_email'))
->to($user->getEmail())
->htmlTemplate('email/registration.html.twig')
->context(['user' => $user]);
$mailer->send($message);
$this->addFlash('notice_success', $translator->trans('flash_registration_03', [], 'website'));
return $this->redirectToRoute('homepage');
}
else
$this->addFlash('notice_warning', $translator->trans('flash_registration_04', [], 'website'));
}
return $this->render('default/registration.html.twig', array(
'form' => $form->createView()
));
}
/**
* @Route({"en":"/create-password/{oneTimeCode}", "it":"/crea-password/{oneTimeCode}"}, name="password_creation", requirements={"oneTimeCode" = "[\w\d]{32}"})
*/
public function passwordCreation(Request $request, $oneTimeCode, ValidatorInterface $validator, UserPasswordHasherInterface $passwordHasher, TranslatorInterface $translator)
{
//DISCONNETTO L'UTENTE SE CONNESSO
$this->get('security.token_storage')->setToken(null);
$em = $this->mr->getManager();
$user = $em->getRepository('App\Entity\User')->findOneByOneTimeCode($oneTimeCode);
$now = new \DateTime('now');
$form = $this->createForm(PasswordCreationType::class, $user, array('locale' => $request->getLocale()));
$form->handleRequest($request);
if($form->isSubmitted()){
$valid = true;
$valid = ValidationService::validateNotBlank($validator, $translator, $form->get('password'));
if($valid){
$psw = $form->get('password')->getData();
$count = 0;
if(preg_match('/[0-9]/', $psw)) $count++;
if(preg_match('/[a-z]/', $psw)) $count++;
if(preg_match('/[A-Z]/', $psw)) $count++;
if(preg_match('/[\!\#\$\&\(\)\.\+\-_]/', $psw)) $count++;
if($count < 3)
{
$this->addFlash('notice_warning', $translator->trans('flash_create_psw_01', [], 'website'));
$valid = false;
}
}
if($valid && $form->isValid()){
$password = $passwordHasher->hashPassword($user, $form->get("password")->getData());
$user->setPassword($password);
$em->flush();
$this->addFlash('notice_success', $translator->trans('flash_create_psw_02', [], 'website'));
return $this->redirectToRoute("homepage");
}
}
return $this->render('default/password_create.html.twig', array(
'oneTimeCode' => $oneTimeCode,
'form' => $form->createView()
));
}
}