<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Hackzilla\PasswordGenerator\Generator\ComputerPasswordGenerator;
use Symfony\Component\HttpKernel\KernelInterface;
use Symfony\Component\Security\Guard\GuardAuthenticatorHandler;
// Entités
use App\Entity\User;
use App\Form\ChangePasswordType;
use App\Security\LoginFormAuthenticator;
class SecurityController extends AbstractController
{
/**
* @Route("/contacts/admin/connectAs/{id}", requirements={"id"="\d+"}, options={"expose"=true}, name="connectAs")
*/
public function connectAs(User $user, Request $request, GuardAuthenticatorHandler $guardHandler, LoginFormAuthenticator $authenticator) {
$this->get('security.token_storage')->setToken(null);
$request->getSession()->invalidate();
return $guardHandler->authenticateUserAndHandleSuccess(
$user,
$request,
$authenticator,
'main'
);
}
/**
* @Route("/login", name="app_login")
*/
public function login(AuthenticationUtils $authenticationUtils): Response
{
// 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("/contacts/changePwd", options={"expose"=true}, methods={"POST", "GET"}, name="changePwd")
*/
public function changePwd(Request $request, UserPasswordEncoderInterface $passwordEncoder)
{
$em = $this->getDoctrine()->getManager();
$user = $this->getUser();
$form = $this->createForm(ChangePasswordType::class, $user);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid())
{
$oldPassword = $request->request->get('change_password')['oldPassword'];
// Si l'ancien mot de passe est bon on peut le changer
if ( $passwordEncoder->isPasswordValid($user, $oldPassword) )
{
$newEncodedPassword = $passwordEncoder->encodePassword($user, $user->getPlainPassword());
$user->setPassword($newEncodedPassword);
$em->persist($user);
$em->flush();
return new JsonResponse(['result' => 'ancien mot de passe ok']);
}
else
return new JsonResponse(['result' => 'ancien mot de passe pas bon']);
}
// Rendu
return $this->render('security/changePasswordForm.html.twig', [
'form' => $form->createView(),
'user' => $user,
]);
}
/**
* @Route("/resetPwd", options={"expose"=true}, methods={"POST", "GET"}, name="resetPwd")
*/
public function resetPwd(Request $request, UserPasswordEncoderInterface $passwordEncoder, \Swift_Mailer $mailer, KernelInterface $kernel)
{
if ( $kernel->getEnvironment() == 'dev')
sleep(1);
// Check du token
$submittedToken = $request->request->get('_csrf_reset_token');
if ( !$this->isCsrfTokenValid('reset-password', $submittedToken) ) {
//$result = ['status' => 'fail', 'content' => 'token invalide'];
$result = ['status' => 'success', 'content' => ''];
return new JsonResponse($result);
}
// Check du mail
$email = $request->request->get('emailInput');
$em = $this->getDoctrine()->getManager();
$user = $em->getRepository(User::class)->findOneBy(['email' => $email]);
if ( $user )
{
// Création d'un nouveau mot de passe
$generator = new ComputerPasswordGenerator();
$generator
->setUppercase()
->setLowercase()
->setNumbers()
->setSymbols(false)
->setLength(12);
$password = $generator->generatePassword();
$newEncodedPassword = $passwordEncoder->encodePassword($user, $password);
$user->setPassword($newEncodedPassword);
// Préparation du mail à envoyer
$content = $this->renderView('security/userResetPasswordMail.html.twig', ['password' => $password]);
$message = (new \Swift_Message())
->setFrom('contact@centre-microkine.fr')
->setTo($user->getEmail())
->setSubject('Centre de Micropraxie : Nouveau mot de passe')
->setBody($content, 'text/html')
;
// Envoi du mot de passe par mail
try
{
$mailerResult = $mailer->send($message, $errors);
}
catch(\Swift_TransportException $e)
{
$exceptionMessage = $e->getMessage() ;
}
// Gestion des erreurs d'envoi de mail :
if ( isset($exceptionMessage) )
$reponse = ['status' => 'fail', 'message' => "Echec de l'envoi de mail"];
elseif ( $mailerResult === 0 )
$reponse = ['status' => 'fail', 'message' => "Echec de l'envoi de mail"];
elseif ( $mailerResult === 1 )
{
$reponse = ['status' => 'success', 'message' => "Nouveau mot de passe envoyé"];
$em->flush();
}
else
$reponse = ['status' => 'fail', 'message' => "Echec de l'envoi de mail"];
}
// mot de passe inconnu
else
$reponse = ['status' => 'success', 'message' => ""];
// $reponse = ['status' => 'fail', 'message' => "echec envoi de mail", 'user' => $user->displayName(), 'result' => $result];
// Rendu
return new JsonResponse($reponse);
}
}