<?php
namespace App\Controller;
use App\Entity\AdminMaintenance;
use App\Entity\Logactivity;
use App\Entity\Pages;
use App\Entity\User;
use App\Form\UserType;
use Doctrine\Persistence\ManagerRegistry;
use Symfony\Bridge\Twig\Mime\TemplatedEmail;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\PasswordHasher\Hasher\PasswordHasherFactoryInterface;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasher;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
use Scheb\TwoFactorBundle\Security\TwoFactor\Provider\Google\GoogleAuthenticatorInterface;
use App\Controller\DGSMailsController;
/**
* @Route("/dgs/cnx")
*/
class SecurityController extends AbstractController
{
public function __construct(ManagerRegistry $doctrine, DGSMailsController $DGSMailsController) {
$this->doctrine = $doctrine;
$this->DGSMailsController = $DGSMailsController;
}
/**
* @Route("/dgs-enregistrement", name="registration")
*/
public function registration(Request $request,PasswordHasherFactoryInterface $passwordHasherFactory, GoogleAuthenticatorInterface $googleAuthenticator): Response // OK Gauthier
{
//On désactive l'inscription
return $this->redirectToRoute('app_login');
//On va créer le formulaire pour User
$user = new User();
$form = $this->createForm(UserType::class, $user);
$form->handleRequest($request);
if ($form->isSubmitted()) {
//Token
$submittedToken = $request->get('user');
if ( $form->isValid() && $this->isCsrfTokenValid('LRMYDu5alu', $submittedToken['_token']) )
{
//On récupere les données
$user = $form->getData();
//On encrypt le mot de pass
// Encode the plain password, and set it.
$passwordHasher = new UserPasswordHasher($passwordHasherFactory);
$encodedPassword = $passwordHasher->hashPassword(
$user,
$form->get('password')->getData()
);
$user->setPassword($encodedPassword);
//On lui defini un role
$user->setRoles( array('ROLE_USER') );
$user->setUsername($user->getEmail());
//2Fa
//$user->setGoogleAuthenticatorSecret($googleAuthenticator->generateSecret());
$user->setEmailAuthenticationCode(random_int(100000, 9999999));
$user->setGoogleAuthenticatorSecret('');
//On écrit dans la BDD
$entityManager = $this->doctrine->getManager();
$entityManager->persist($user);
$entityManager->flush();
//Mail
$this->DGSMailsController->submitMailToGeneral($user, "Confirmation inscription",'');
$this->DGSMailsController->submitMailToGeneral('', "Admin - Nouvelle inscription",'');
$this->addFlash('success', "Votre inscription a été enregistrée !");
return $this->redirectToRoute('app_login');
} else {
$mess = "Une erreur s'est produite. Essayez de recharger la page.";
if($request->query->get('registration')){
$this->DGSMailsController->submitMailToAdmin($user);
$mess = $mess . " - 1";
}
$this->addFlash('error', $mess);
}
}
return $this->render('security/registration.html.twig', [
'csrf_token' => 'LRMYDu5alu',
'form' => $form->createView()
]);
}
/**
* @Route("/dgs-login", name="app_login")
*/
public function login(AuthenticationUtils $authenticationUtils): Response // OK Gauthier
{
//Si déjà identifié
if ($this->getUser()) {
return $this->redirectToRoute('admin');
}
// get the login error if there is one
$error = $authenticationUtils->getLastAuthenticationError();
// last username entered by the user
$lastUsername = $authenticationUtils->getLastUsername();
return $this->render('security/login.html.twig', [
'last_username' => $lastUsername,
'error' => $error
]);
}
/**
* @Route("/dgs-logout", name="app_logout")
*/
public function logout() // OK Gauthier
{
throw new \LogicException('This method can be blank - it will be intercepted by the logout key on your firewall.');
}
/**
* @Route("/ip/activate", name="dgsipactivate")
*/
public function dgsipactivate(Request $request, ManagerRegistry $doctrine, MailerInterface $mailer): Response // OK Gauthier
{
//Variables
$return = false;
$action = $request->get('action');
$ip = "";
$em = $doctrine->getManager();
//On récupére les info dans twig.yaml
$twig = $this->container->get('twig');
$globals = $twig->getGlobals();
if($action == "go") {
//On va ajouter l'IP à la base de donnée
if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
$ip = $_SERVER['HTTP_CLIENT_IP'];
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
$ip = $_SERVER['REMOTE_ADDR'];
}
//On recherche la BDD
$EntityDgstools = $em->getRepository(AdminMaintenance::class)->findOneBy(array('id'=>1));
if($EntityDgstools && $ip != "") {
//On va rechercher la liste des IPs
$listIps = $EntityDgstools->getIpmaintenance();
$listIpsArray = explode(",", $listIps);
//On boucle
$listIpsString = $ip;
foreach($listIpsArray as $listIpDetail) {
if($listIpDetail != $ip) {
$listIpsString = $listIpsString .",".$listIpDetail;
}
}
$EntityDgstools->setIpmaintenance($listIpsString);
$em->persist($EntityDgstools);
$em->flush();
//On envoi un mail
$email = (new TemplatedEmail())
->from($globals['email_reset_dgs'])
->to($globals['email_reset_dgs'])
->subject('['.$globals['nom_normalise'].'] - IP débloqué')
->htmlTemplate('emails/ip.html.twig')
->context([
'message' => "L'IP suivante vient d'être débloquée : " . $ip
])
;
$mailer->send($email);
}
$return = true;
}
return $this->render('admin/dgstools/ipactivation.html.twig', [
"return" => $return,
"ip" => $ip
]);
}
}