<?php
namespace App\Controller;
use App\Entity\SiteUser;
use App\Entity\Users;
use App\Form\OtpChekType;
use App\Form\ProfilFormType;
use App\Form\SecurityType;
use App\Form\SiteUserType;
use App\Form\UpdatePasswordType;
use App\Form\UserIscriptionType;
use App\Service\OtpCodeHandler;
use App\Service\SendNotificationService;
use App\Service\Verify\TwilioService;
use App\Utils\LogManager;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\Persistence\ManagerRegistry;
use Exception;
use phpDocumentor\Reflection\Types\This;
use Psr\Log\LoggerInterface;
use Symfony\Bridge\Twig\Mime\TemplatedEmail;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Mime\Email;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
use Symfony\Component\Uid\Uuid;
use Symfony\Contracts\HttpClient\HttpClientInterface;
use Twig\Environment;
class SecurityController extends AbstractController
{
private const MAX_ATTEMPTS = 3;
private const BLOCKED_DURATION = 600;
private EntityManagerInterface $em;
private LoggerInterface $logger;
private HttpClientInterface $client;
private MailerInterface $mailer;
private $twig;
private OtpCodeHandler $otpCodeHandler;
private ManagerRegistry $registry;
private SendNotificationService $sendNotificationService;
private TwilioService $twilioService;
public function __construct(
HttpClientInterface $client,
EntityManagerInterface $em,
LoggerInterface $logger,
MailerInterface $mailer,
Environment $twig,
OtpCodeHandler $otpCodeHandler,
SendNotificationService $sendNotificationService,
ManagerRegistry $registry,
TwilioService $twilioService
)
{
$this->em = $em;
$this->logger = $logger;
$this->mailer = $mailer;
$this->twig = $twig;
$this->client = $client;
$this->otpCodeHandler = $otpCodeHandler;
$this->sendNotificationService = $sendNotificationService;
$this->registry = $registry;
$this->twilioService = $twilioService;
}
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]);
}
public function logoutCustom(Request $request, TokenStorageInterface $tokenStorage): RedirectResponse
{
LogManager::save("inconnu", "Déconnexion réussie");
if ($this->getUser() instanceof UserInterface) {
// Déconnectez l'utilisateur en supprimant le token
$tokenStorage->setToken(null);
}
return $this->redirectToRoute('app_user_logout');
}
public function logout(Request $request, TokenStorageInterface $tokenStorage)
{
LogManager::save("inconnu", "Déconnexion réussie");
if ($this->getUser() instanceof UserInterface) {
// Déconnectez l'utilisateur en supprimant le token
$tokenStorage->setToken(null);
}
return $this->redirectToRoute('homepage');
}
public function resetPassword(): Response
{
return $this->render('security/reset_password.html.twig', array(
'form' => '',
));
}
public function genOtp()
{
$n = 6;
$generator = "1357902468";
$result = "";
for ($i = 1; $i <= $n; $i++) {
$result .= substr($generator, (rand() % (strlen($generator))), 1);
}
return $result;
}
public function sendSMS($otp, $phoneNumber)
{
$response = "KO";
try {
$response = $this->client->request('GET', 'https://api.budgetsms.net/sendsms/', [
// these values are automatically encoded before including them in the URL
'query' => [
'username' => 'papove01',
'userid' => '18671',
'handle' => '3b699dc89c88cd862044fab30349a14b',
'msg' => 'Bienvenue sur TownSys! Votre code de confirmation est: ' . $otp,
'from' => 'TownSys',
'to' => $phoneNumber,
],
]);
return $response;
} catch (Exception $e) {
$this->logger->info('>>>>>>>>>', ["------------------------------------------------"]);
$this->logger->info('SMS sending Exception', [$e->getMessage()]);
return $response;
}
}
public function inscriptionBis(Request $request, UserPasswordHasherInterface $passwordHasher, MailerInterface $mailer): Response
{
$user = new Users();
$form = $this->createForm(UserIscriptionType::class, $user);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$verificationMode = $form->get('verificationMode')->getData();
$userMail = $user->getMail();
$user->setPassword(
$passwordHasher->hashPassword(
$user,
$form->get('password')->getData()
)
);
$user->setFirstLogin(true);
$otp = $this->genOtp();
$user->setUserType(4);
$user->setIsAuthority(false);
$user->setOtp($otp);
$user->setStatus(0);
$user->setTimeOtp((new \DateTime())->add(new \DateInterval('P3M')));
$user->setUID(Uuid::v3(
Uuid::fromString(Uuid::NAMESPACE_OID),
$user->getMail() ?? uniqid()));
$em = $this->registry->getManager();
$em->persist($user);
$em->flush();
// ajouter le symbole + devant le numéro de téléphone
$phoneNumber = $user->getTelephone();
try {
if ($verificationMode == "sms") {
if (substr($phoneNumber, 0, 1) != "+") {
$phoneNumber = "+" . $phoneNumber;
}
$verification = $this->twilioService->startVerification($phoneNumber, $verificationMode);
$this->logger->info('REPONSE API SMS', ["----------------------------------------------------------------------------------------------------------------"]);
$this->logger->info('reponse sms', [$verification]);
if (!$verification->isValid()) {
$em->remove($user);
// put the errors array in the flash message
$this->addFlash('user_inscription_fail', $verification->getErrors());
return $this->redirectToRoute('app_user_inscription');
}
} else {
$emailTemplate = (new TemplatedEmail())
->from($this->getParameter('mailFrom'))
->to($userMail)
->subject('Confirmation Inscription sur MOKANDA')
->text('inscription effectué avec succès!')
->htmlTemplate('email/verification_code_email.html.twig')
->context([
'user' => $user,
'otp' => $otp
]);
$mailer->send($emailTemplate);
$this->addFlash('message', 'le message a été envoyé');
$this->logger->info('After send mail code', []);
}
$otpData = [
'verificationMode' => $verificationMode,
'user' => $user,
'attempts' => 1,
];
$key = "otpData_" . $user->getId();
$request->getSession()->set($key, $otpData);
$request->getSession()->set('user_phone', $phoneNumber);
$request->getSession()->set('user_mail', $userMail);
} catch (Exception $e) {
//throw $th;
$this->logger->info('In Exception', [$e->getMessage()]);
$this->addFlash('user_inscription_fail', 'Une erreur est survenur lors de l\'inscription, prière véfifier vorte connexion');
return $this->redirectToRoute('app_user_inscription');
} catch (TransportExceptionInterface $e) {
$this->logger->info('In Exception transport', [$e->getMessage()]);
// some error prevented the email sending; display an
// error message or try to resend the message
$this->addFlash('user_inscription_fail', 'Une erreur est survenur lors de l\'inscription, prière contactez le support');
return $this->redirectToRoute('app_user_inscription');
}
$this->addFlash('user_inscription_success', 'Votre compte utilisateur a été créé avec succès, prière de vous connceter!');
return $this->redirectToRoute('app_user_otp_check', ['user_id' => $user->getUID()]);
}
return $this->render('security/inscription.html.twig', [
'form' => $form->createView(),
]);
}
public function inscription(Request $request, UserPasswordHasherInterface $passwordHasher, MailerInterface $mailer): Response
{
$user = new Users();
$form = $this->createForm(UserIscriptionType::class, $user);
$form->handleRequest($request);
$verificationMode = null;
if ($form->isSubmitted() && $form->isValid()) {
$verificationMode = $form->get('verificationMode')->getData();
$request->getSession()->set('verificationMode', $verificationMode);
$userMail = $user->getMail();
$user->setPassword(
$passwordHasher->hashPassword(
$user,
$form->get('password')->getData()
)
);
$user->setFirstLogin(true);
$otp = $this->genOtp();
$user->setUserType(4);
$user->setIsAuthority(false);
$user->setOtp($otp);
$user->setStatus(0);
$user->setTimeOtp((new \DateTime())->add(new \DateInterval('P3M')));
$em = $this->registry->getManager();
$em->persist($user);
$em->flush();
// do anything else you need here, like send an email
try {
if ($verificationMode == "sms") {
$response = $this->sendSMS($otp, $user->getTelephone());
$this->logger->info('REPONSE API SMS', ["----------------------------------------------------------------------------------------------------------------"]);
$this->logger->info('reponse sms', [$response]);
} else {
// $email = (new Email())
// ->from('[email protected]')
// ->to($user->getMail())
// //->to( '' )
// ->subject('Confirmation Inscription sur MOKANDA')
// ->text('inscription effectué avec succès!')
// ->html('<p> Cher, ' . $userMail . " Nous avons reçu votre demande d'inscription sur la plateforme MOKANDA-RDC www.mokanda-rdc.com , voici votre code de confirmation: " . $otp . '</p>');
//
// $mailer->send($email);
// Envoyer un mail de réponse à l'internaute
$emailTemplate = (new TemplatedEmail())
->from($this->getParameter('mailFrom'))
->to($userMail)
->subject('Confirmation Inscription sur MOKANDA')
->text('inscription effectué avec succès!')
->htmlTemplate('email/verification_code_email.html.twig')
->context([
'user' => $user,
'otp' => $otp
]);
$mailer->send($emailTemplate);
$this->addFlash('message', 'le message a été envoyé');
$this->logger->info('After send mail code', []);
}
$otpData = [
'verificationMode' => $verificationMode,
'user' => $user,
'attempts' => 1
];
$key = "otpData_" . $user->getId();
$request->getSession()->set($key, $otpData);
} catch (Exception $e) {
//throw $th;
$this->logger->info('In Exception', [$e->getMessage()]);
$this->addFlash('user_inscription_fail', 'Une erreur est survenur lors de l\'inscription, prière véfifier vorte connexion');
return $this->redirectToRoute('app_user_inscription');
} catch (TransportExceptionInterface $e) {
$this->logger->info('In Exception transport', [$e->getMessage()]);
// some error prevented the email sending; display an
// error message or try to resend the message
$this->addFlash('user_inscription_fail', 'Une erreur est survenur lors de l\'inscription, prière contactez le support');
return $this->redirectToRoute('app_user_inscription');
}
$this->addFlash('user_inscription_success', 'Votre compte utilisateur a été créé avec succès, prière de vous connceter!');
return $this->redirectToRoute('app_user_otp_check', ['user_id' => $user->getId()]);
}
return $this->render('security/inscription.html.twig', [
'form' => $form->createView(),
]);
}
public function resendOtpCode(Users $user, Request $request)
{
$formOtp = $this->createForm(OtpChekType::class);
$formOtp->handleRequest($request);
$id = $user->getId();
$key = 'otpData_' . $id;
$otpData = $request->getSession()->get($key);
try {
if ($otpData >= 3) {
throw new Exception("Vous avez atteint le nombre maximun des tentatives d'envoi de code otp");
}
$this->otpCodeHandler->sendCode($user);
$this->addFlash('message', 'le message a été envoyé');
$this->logger->info('After send mail code', []);
$this->addFlash('send_code_success', 'Un nouveau code vous a été renvoyé');
} catch (Exception|TransportExceptionInterface $e) {
$this->logger->info('In Exception transport', [$e->getMessage()]);
$this->addFlash('send_code_error', $e->getMessage());
}
return $this->render(
'security/otp_verification.html.twig',
[
'formOtp' => $formOtp->createView(),
'user' => $user
]
);
}
/**
* @param Request $request
* @param MailerInterface $mailer
* @return RedirectResponse
*/
public function resendOtpCodeBis(Request $request, MailerInterface $mailer): RedirectResponse
{
$uID = $request->attributes->get('user');
$user = $this->registry->getRepository(Users::class)->findOneBy(['uID' => $uID]);
if (!$user) {
throw $this->createNotFoundException(
'No user found for id ' . $uID
);
}
$key = 'otpData_' . $user->getId();
$otpData = $request->getSession()->get($key);
if (!$otpData) {
return $this->redirectToRoute('app_403_page');
}
$verificationMode = $otpData['verificationMode'];
if ($verificationMode == 'sms') {
$verify = $this->twilioService->startVerification($user->getTelephone(), $verificationMode);
if (!$verify->isValid()) {
$this->addFlash('send_code_error', $verify->getErrors());
} else {
$this->addFlash('send_code_success', 'Un nouveau code vous a été renvoyé');
}
return $this->redirectToRoute('app_user_otp_check', ['user_id' => $uID]);
} else {
$otp = $this->genOtp();
$user->setOtp($otp);
$user->setStatus(0);
$user->setTimeOtp((new \DateTime())->add(new \DateInterval('P3M')));
$em = $this->registry->getManager();
$em->persist($user);
$em->flush();
try {
if ($otpData['attempts'] > 3) {
$otpData['attempts'] = 0;
$key = "otpData_" . $user->getId();
$request->getSession()->set($key, $otpData);
$this->addFlash('send_code_error', 'Vous avez atteint le nombre maximun des tentatives d\'envoi de code otp réssayez plus tard');
} else {
$email = (new Email())
->from($this->getParameter('mailFrom'))
->to($user->getMail())
->subject('Verification Compte Utilisateur')
->text('Vérification de vôtre compte utilisateur')
->html('<p> Cher, ' . $user->getMail() . "<br> Nous avons reçu votre demande d'inscription sur la plateforme MOKANDA-RDC www.mokanda-rdc.com , voici votre code de confirmation: " . $otp . '</p>');
$mailer->send($email);
$otpData['attempts'] += 1;
$request->getSession()->set($key, $otpData);
$this->addFlash('send_code_success', 'Un nouveau code vous a été renvoyé');
}
return $this->redirectToRoute('app_user_otp_check', ['user_id' => $user->getUID()]);
} catch (TransportExceptionInterface $e) {
$this->logger->info('In Exception transport', [$e->getMessage()]);
$this->addFlash('user_inscription_fail', 'Une erreur est survenue lors de l\'inscription, prière contactez le support');
return $this->redirectToRoute('app_user_inscription');
}
}
}
public function otpCheckBis(Request $request)
{
$userPhone = $request->getSession()->get('user_phone');
$user = $this->registry->getRepository(Users::class)->findOneBy([
'uID' => $request->get('user_id'),
'isDeleted' => false,
]);
if (!$user) {
return $this->redirectToRoute('app_403_page');
}
// check if optData is in session if not redirect to 403 page
$otpData = $request->getSession()->get('otpData_' . $user->getId());
if (!$otpData) {
return $this->redirectToRoute('app_403_page');
}
$formOtp = $this->createForm(OtpChekType::class);
$formOtp->handleRequest($request);
if ($formOtp->isSubmitted() && $formOtp->isValid()) {
$otpParam = $formOtp->get('otp')->getData();
// selon le mode de vérification on vérifie le code otp
if ($otpData["verificationMode"] == "sms") {
$verify = $this->twilioService->checkVerification($userPhone, $otpParam);
$this->logger->info('REPONSE API SMS', ["----------------------------------------------------------------------------------------------------------------"]);
$this->logger->info('reponse sms', [$verify]);
if ($verify->isValid()) {
$user->setStatus(1);
$entityManager = $this->registry->getManager();
$entityManager->persist($user);
$entityManager->flush();
$this->addFlash('otp_chek_succed', 'Votre compte utilisateur a été vérifié avec succès, vous pouvez vous connecter!');
return $this->redirectToRoute('app_user_login');
} else {
$this->addFlash('otp_chek_fail', 'votre code otp est incorrect ou a expiré!!');
}
} else {
if ($otpParam != $user->getOtp()) {
$this->logger->info('Mauvais OTP', [$otpParam]);
$this->addFlash('otp_chek_fail', 'votre code otp est incorrect ou a expiré!!');
} else {
$user->setStatus(1);
$entityManager = $this->registry->getManager();
$entityManager->persist($user);
$entityManager->flush();
$this->addFlash('otp_chek_succed', 'Votre compte utilisateur a été vérifié avec succès, vous pouvez vous connecter!');
return $this->redirectToRoute('app_user_login');
}
}
}
return $this->render('security/otp_verification.html.twig', [
'userId' => $user->getUID(),
'formOtp' => $formOtp->createView(),
]
);
}
public function resendOtpCodeNew(Request $request, MailerInterface $mailer): Response
{
$uID = $request->attributes->get('user');
$user = $this->registry->getRepository(Users::class)->findOneBy(['uID' => $uID]);
if (!$user) {
throw $this->createNotFoundException(
'No user found for id ' . $user->getId()
);
}
$otp = $this->genOtp();
$formOtp = $this->createForm(OtpChekType::class);
$formOtp->handleRequest($request);
$key = 'otpData_' . $user->getId();
$otpData = $request->getSession()->get($key);
$user->setOtp($otp);
$user->setStatus(0);
$user->setTimeOtp((new \DateTime())->add(new \DateInterval('P3M')));
$em = $this->registry->getManager();
$em->persist($user);
$em->flush();
try {
if ($otpData === null) {
$otpData = [
'verificationMode' => "mail",
'user' => $user,
'attempts' => 1
];
}
if ($otpData['attempts'] > 3) {
$otpData['attempts'] = 0;
$key = "otpData_" . $user->getId();
$request->getSession()->set($key, $otpData);
$this->addFlash('send_code_error', 'Vous avez atteint le nombre maximun des tentatives d\'envoi de code otp réssayez plus tard');
} else {
$email = (new Email())
->from($this->getParameter('mailFrom'))
->to($user->getMail())
->subject('Verification Compte Utilisateur')
->text('Vérification de vôtre compte utilisateur')
->html('<p> Cher, ' . $user->getMail() . "<br> Nous avons reçu votre demande d'inscription sur la plateforme MOKANDA-RDC www.mokanda-rdc.com , voici votre code de confirmation: " . $otp . '</p>');
$mailer->send($email);
$otpData['attempts'] += 1;
$key = "otpData_" . $user->getId();
$request->getSession()->set($key, $otpData);
$this->addFlash('send_code_success', 'Un nouveau code vous a été renvoyé');
}
return $this->redirectToRoute('app_user_otp_check', ['user_id' => $user->getId()]);
} catch (TransportExceptionInterface $e) {
$this->logger->info('In Exception transport', [$e->getMessage()]);
// some error prevented the email sending; display an
// error message or try to resend the message
$this->addFlash('user_inscription_fail', 'Une erreur est survenue lors de l\'inscription, prière contactez le support');
return $this->redirectToRoute('app_user_inscription');
}
// return $this->render(
// 'security/otp_verification.html.twig',
// [
// 'formOtp' => $formOtp->createView(),
// 'user' => $user
// ]
// );
}
public function add(Request $request, UserPasswordHasherInterface $passwordHasher): Response
{
if ($this->getUser()->getUserType() != 6 && $this->getUser()->getUserType() != 1) {
$this->addFlash('workspace_alert_warning', "Vous ne pouvez pas accéder à la ressource sollicitée");
if ($this->getUser()->getUserType() != 4) {
return $this->redirectToRoute('app_core_workspace');
} else {
return $this->redirectToRoute('app_core_workspace_surfer');
}
}
$user = new Users();
$form = $this->createForm(SecurityType::class, $user);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$user->setPassword(
$passwordHasher->hashPassword(
$user,
'1234'
)
);
$user->setFirstLogin(true);
$entityManager = $this->registry->getManager();
$entityManager->persist($user);
$entityManager->flush();
$notificationMessage = "L'utilisateur " . $user->getUsername() . " a été créé et affecté à " . $user->getSite()->getLabel() . " par " . $this->getUser()->getUserName();
$this->sendNotificationService->sendMailNotification("Utilisateur Créé", $notificationMessage);
// do anything else you need here, like send an email
$this->addFlash('update_user_success', 'Le compte utilisateur a été créé avec succès !');
return $this->redirectToRoute('app_user_register');
}
return $this->render('security/add.html.twig', [
'userForm' => $form->createView(),
]);
}
public function update(Request $request)
{
if ($this->getUser()->getUserType() != 6 && $this->getUser()->getUserType() != 1) {
$this->addFlash('workspace_alert_warning', "Vous ne pouvez pas accéder à la ressource sollicitée");
return $this->redirectToRoute('app_core_workspace');
}
$user = $this->registry->getRepository(Users::class)->findOneBy([
'id' => $request->get('user_id'),
//'isDeleted' => false,
]);
if ($user === null) {
$this->addFlash('not_found_user', 'Le compte utilisateur ' . ucfirst($request->get('user_id')) . ' n\'a pas été trouvé');
return $this->redirectToRoute('app_user_register');
}
$username = $user->getUsername();
$login = $user->getLogin();
$userType = $this->getUserTypeLabel($user->getUserType());
$currentSite = $user->getSite();
$mail = $user->getMail();
$telephone = $user->getTelephone();
$userToUpdate = $user;
$notificationMessage = "L'utilisateur " . $user->getUsername() . " avec l'Id " . $user->getId() . " a été modifié par " . $this->getUser()->getUserName();
$form = $this->createForm(SecurityType::class, $user);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$em = $this->registry->getManager();
$em->persist($user);
$em->flush();
//NOTIFICATION MAIL DES MODIFICATIONS
if ($username !== $user->getUserName()) {
$notificationMessage = $notificationMessage . "<br> Nom de l'utilisateur: " . $username . "-->" . $user->getUserName();
}
if ($login !== $user->getLogin()) {
$notificationMessage = $notificationMessage . "<br> Login: " . $login . "-->" . $user->getLogin();
}
if ($userType !== $user->getUserType()) {
$newProfile = $this->getUserTypeLabel($user->getUserType());
$notificationMessage = $notificationMessage . "<br> Profile: " . $userType . "-->" . $newProfile;
}
if ($currentSite != null && $user->getSite() != null) {
if ($currentSite->getId() !== $user->getSite()->getId()) {
$notificationMessage = $notificationMessage . "<br> Site d'affectation: " . $currentSite->getLabel() . "-->" . $user->getSite()->getLabel();
}
}
if ($currentSite == null && $user->getSite() != null) {
if ($userToUpdate->getSite()->getId() !== $user->getSite()->getId()) {
$notificationMessage = $notificationMessage . "<br> Site d'affectation: " . $user->getSite()->getLabel();
}
}
if ($mail !== $user->getMail()) {
$notificationMessage = $notificationMessage . "<br> Adresse email: " . $mail . "-->" . $user->getMail();
}
if ($telephone !== $user->getTelephone()) {
$notificationMessage = $notificationMessage . "<br> Téléphone: " . $telephone . "-->" . $user->getTelephone();
}
$this->logger->info('Contenu du message', [$notificationMessage]);
$this->sendNotificationService->sendMailNotification("Utilisateur modifié", $notificationMessage);
$this->addFlash('update_user_success', 'Le compte utilisateur a été modifié avec succès !');
return $this->redirectToRoute('app_user_register');
}
return $this->render('security/add.html.twig', [
'userForm' => $form->createView(),
'user' => $user,
]);
}
public function removeUser(Request $request)
{
$user = $this->registry->getRepository(Users::class)->findOneBy([
'id' => $request->get('user_id'),
//'isDeleted' => false,
]);
$userDeleted = $this->getUser()->getId();
if ($user === null) {
$this->addFlash('not_found_user', 'Le compte utilisateur ' . ucfirst($request->get('user_id')) . ' n\'a pas été trouvé');
return $this->redirectToRoute('app_user_register');
}
$em = $this->registry->getManager();
$user->setIsDeleted(true);
$user->setStatus(false);
$user->setDeletedDate(new \DateTime());
$user->setUserDeleted($userDeleted);
$em->persist($user);
$em->flush();
$this->addFlash('su_alert_success', "L'utilisateur " . $user->getMail() . " a été desactivé avec succès");
return $this->redirectToRoute('app_user_register');
}
public function activateRoleUser(Request $request)
{
$users = $this->registry->getRepository(Users::class)->findBy([
'userType' => $request->get('role_id'),
'isDeleted' => false,
]);
if ($users === null) {
$this->addFlash('not_found_user', 'Aucun compte utilisateur avec le rôle ' . ucfirst($request->get('role_id')) . ' n\'a été trouvé');
return $this->redirectToRoute('app_user_register');
}
$em = $this->registry->getManager();
foreach ($users as $u) {
$u->setStatus(true);
$em->persist($u);
}
$em->flush();
$this->addFlash('su_alert_success', "Les comptes utilisateurs ont été activés avec succès");
return $this->redirectToRoute('app_user_register');
}
public function disableRoleUser(Request $request)
{
$users = $this->registry->getRepository(Users::class)->findBy([
'userType' => $request->get('role_id'),
'isDeleted' => false,
]);
if ($users === null) {
$this->addFlash('not_found_user', 'Aucun compte utilisateur avec le rôle ' . ucfirst($request->get('role_id')) . ' n\'a été trouvé');
return $this->redirectToRoute('app_user_register');
}
$em = $this->registry->getManager();
foreach ($users as $u) {
$u->setStatus(false);
$em->persist($u);
}
$em->flush();
$this->addFlash('su_alert_success', "Les comptes utilisateurs ont été désactivés avec succès");
return $this->redirectToRoute('app_user_register');
}
public function getUserTypeLabel($type)
{
$userTypeLabel = "";
switch ($type) {
case 1:
$userTypeLabel = "ADMINISTRATEUR";
break;
case 2:
$userTypeLabel = "AUTORITE";
break;
case 3:
$userTypeLabel = "OPS";
break;
case 4:
$userTypeLabel = "INTERNAUTE";
break;
case 5:
$userTypeLabel = "VALIDATEUR";
break;
case 6:
$userTypeLabel = "SUPER-ADMIN";
break;
case 7:
$userTypeLabel = "UTILISATEUR-RAPPORT";
break;
case 8:
$userTypeLabel = "SUPERVISEUR";
break;
}
return $userTypeLabel;
}
public function updatePassword(Request $request, UserPasswordHasherInterface $passwordHasher, TokenStorageInterface $tokenStorage)
{
$user = $this->registry->getRepository(Users::class)->findOneBy([
'id' => $request->get('user_id'),
'isDeleted' => false,
]);
if ($user === null) {
$this->addFlash('not_found_user', 'Le compte utilisateur ' . ucfirst($request->get('user_id')) . ' n\'a pas été trouvé');
return $this->redirectToRoute('app_core_homepage');
}
// Redirect to homepage when db user is different to session user
if ($user != $this->getUser()) {
return $this->redirectToRoute('app_core_homepage');
}
$updatePasswordForm = $this->createForm(UpdatePasswordType::class);
$updatePasswordForm->handleRequest($request);
if ($updatePasswordForm->isSubmitted() && $updatePasswordForm->isValid()) {
$data = $updatePasswordForm->getData();
$newPassword = $data['password'];
$oldPassword = $data['lastPassword'];
// Empêchez l'utilisateur d'enregistrer à nouveau l'ancien mot de passe
if ($oldPassword === $newPassword) {
$this->addFlash('update_user_danger', 'Ce mot de passe a déjà été utilisé, veuillez saisir un nouveau');
return $this->redirectToRoute('app_user_update_password', ['user_id' => $user->getId()]);
}
$user->setFirstLogin(false);
$user->setUpdatePasswordDate(new \DateTime());
$user->setPassword(
$passwordHasher->hashPassword(
$user,
$newPassword
)
);
$entityManager = $this->registry->getManager();
$entityManager->persist($user);
$entityManager->flush();
if ($this->getUser() instanceof UserInterface) {
// Déconnectez l'utilisateur en supprimant le token
$tokenStorage->setToken(null);
}
// do anything else you need here, like send an email
$this->addFlash('update_user_success', 'Le compte utilisateur a été créé avec succès !');
return $this->redirectToRoute('app_user_login');
}
return $this->render('security/update_password.html.twig', [
'updatePasswordForm' => $updatePasswordForm->createView(),
]);
}
public function forgotPassword(Request $request, MailerInterface $mailer)
{
$user = new Users();
$form = $this->createForm(UserIscriptionType::class, $user, ['is_forgot' => true]);
$form->handleRequest($request);
$verificationMode = null;
if ($form->isSubmitted() && $form->isValid()) {
$verificationMode = $form->get('verificationMode')->getData();
$request->getSession()->set('verificationMode', $verificationMode);
if ($form->isSubmitted() && $form->isValid()) {
$otp = $this->genOtp();
$user = $this->em->getRepository(Users::class)->findOneBy(
[
'mail' => $form->get('plainEmail')->getData()
]
);
if ($user != null) {
$userSendMail = $user->getMail();
if ($user) {
$user->setOtp($otp);
$user->setTimeOtp(new \DateTime());
$this->em->persist($user);
$this->em->flush();
// SEND EMAIL
try {
if ($verificationMode == "sms") {
$response = $this->sendSMS($otp, $user->getTelephone());
$this->logger->info('REPONSE API SMS', ["----------------------------------------------------------------------------------------------------------------"]);
$this->logger->info('reponse sms', [$response]);
} else {
$email = (new Email())
->from($this->getParameter('mailFrom'))
->to($user->getMail())
//->to( '[email protected]' )
->subject('Réinitialisation du mot de passe')
->text('Réinitialisation effectué avec succès!')
->html('<p>Cher ' . $userSendMail . ', nous avons reçu votre demande de réinitialisation de mot de passe sur www.mokanda-rdc.com, voici votre code de confirmation: ' . $otp . '</p>');
$mailer->send($email);
$this->addFlash('message', 'le message a été envoyé');
$this->logger->info('After send mail code', []);
}
$otpData = [
'verificationMode' => $verificationMode,
'user' => $user,
'attempts' => 1
];
$key = "otpData_" . $user->getId();
$request->getSession()->set($key, $otpData);
} catch (\Exception $ex) {
/**
* TO DO
*/
//$this->addFlash('app_user_forgot_password_mail_failed', "Le mail n'a pas été envoyé. ");
}
} else {
$this->addFlash('user_not_found', "Cet utilisateur n'existe pas dans la base de données");
return $this->redirectToRoute('app_user_forgot_password');
}
} else {
$this->addFlash('user_not_found', "Cet utilisateur n'existe pas dans la base de données");
return $this->redirectToRoute('app_user_forgot_password');
}
}
$this->addFlash('app_user_forgot_password_mail_success', "Le mail de réinitialisation a été envoyé avec succès.");
return $this->redirectToRoute('app_user_otp_check_password_update', ['user_id' => $user->getId()]);
}
return $this->render('security/forgot_password.html.twig', [
'form' => $form->createView(),
]);
}
public function updatePasswordPublic(Request $request, UserPasswordHasherInterface $passwordHasher)
{
$user = $this->registry->getRepository(Users::class)->findOneBy([
'id' => $request->get('user_id'),
'isDeleted' => false,
]);
if ($user === null) {
$this->addFlash('not_found_user', 'Le compte utilisateur ' . ucfirst($request->get('user_id')) . ' n\'a pas été trouvé');
return $this->redirectToRoute('app_core_homepage');
}
//if ($this->getUser()->getId() != $user->getId()) {
// $this->addFlash('workspace_alert_warning', "Vous ne pouvez pas accéder à la ressource sollicitée");
//return $this->redirectToRoute('app_core_workspace');
//}
$updatePasswordForm = $this->createForm(UpdatePasswordType::class);
$updatePasswordForm->handleRequest($request);
if ($updatePasswordForm->isSubmitted() && $updatePasswordForm->isValid()) {
// $lastPassword = $updatePasswordForm->get('lastPassword')->getData();
// $encodedLastPassword = $passwordHasher->hashPassword($user, $lastPassword );
// $lastPasswordFromBd = $user->getPassword();
// $mach = $passwordHasher->isPasswordValid($this->getUser(), $encodedLastPassword);
// if ($mach == false ) {
// $this->addFlash('wrongLastPassword', "Votre mot de passe".$encodedLastPassword." est différent de l'ancien, veuillez saisir le mot de passe valide!".$lastPasswordFromBd."");
// return $this->redirectToRoute('app_user_update_password', ['user_id' => $this->getUser()->getId()]);
// }
$user->setFirstLogin(false);
$user->setUpdatePasswordDate(new \DateTime());
$newpassword = $updatePasswordForm->getData('password');
$user->setPassword(
$passwordHasher->hashPassword(
$user,
$newpassword["password"]
)
);
$entityManager = $this->registry->getManager();
$entityManager->persist($user);
$entityManager->flush();
// do anything else you need here, like send an email
$this->addFlash('update_user_success', 'Le mot de passe a été mise à jour avec succès !');
return $this->redirectToRoute('app_user_login');
}
return $this->render('security/update_password_forgot.html.twig', [
'updatePasswordForm' => $updatePasswordForm->createView(),
]);
}
public function otpchekPasswordUpdate(Request $request)
{
$user = $this->registry->getRepository(Users::class)->findOneBy([
'id' => $request->get('user_id'),
//'isDeleted' => false,
]);
$formOtp2 = $this->createForm(OtpChekType::class);
$formOtp2->handleRequest($request);
if ($formOtp2->isSubmitted() && $formOtp2->isValid()) {
$otpParam = $formOtp2->get('otp')->getData();
if ($otpParam != $user->getOtp()) {
$this->logger->info('Mauvais OTP', [$otpParam]);
$this->addFlash('otp_chek_fail', 'votre code otp est incorrect ou a expiré!!');
} else {
$user->setStatus(1);
$entityManager = $this->registry->getManager();
$entityManager->persist($user);
$entityManager->flush();
$this->addFlash('otp_chek_succed', 'Votre compte utilisateur a été vérifié avec succès, vous pouvez vous connecter!');
return $this->redirectToRoute('app_user_update_password_public', ['user_id' => $user->getId()]);
}
}
return $this->render(
'security/otp_verification_update_pw.html.twig',
[
'formOtp2' => $formOtp2->createView(),
'user' => $user
]
);
}
public function view(Request $request)
{
// Interdire l'accès aux utilisateurs non autorisés
if ($this->getUser()->getUserType() != 6) {
$this->addFlash('workspace_alert_warning', "Vous ne pouvez pas accéder à la ressource sollicitée");
return $this->redirectToRoute('app_core_workspace');
}
$user = $this->registry->getRepository(Users::class)->findOneBy([
'id' => $request->get('user_id'),
//'isDeleted'=> false,
]);
if ($user === null) {
$this->addFlash('not_found_user', 'Le compte utilisateur ' . ucfirst($request->get('user_id')) . ' n\'a pas été trouvé');
return $this->redirectToRoute('app_user_register');
}
//Récupération des sites de l'utilisateur
$sus = $this->registry->getRepository(SiteUser::class)->findBy([
'user' => $user->getId(),
'isDeleted' => false
]);
$em = $this->registry->getManager();
$su = new SiteUser();
$suForm = $this->createForm(SiteUserType::class, $su);
$suForm->handleRequest($request);
if ($suForm->isSubmitted() && $suForm->isValid()) {
$suExist = $this->registry->getRepository(SiteUser::class)->findBy([
'user' => $user->getId(),
'site' => $su->getSite()->getId(),
'isDeleted' => false
]);
if (!is_null($suExist) && count($suExist) > 0) {
$this->addFlash('su_alert_warning', "Le site " . $su->getSite()->getLabel() . " est déjà affecté, impossible de l'affecter une deuxième fois au même utilisateur");
return $this->redirectToRoute('app_user_view', [
'user_id' => $user->getId(),
]);
} else {
$su->setIsDeleted(false);
$su->setUserCreate($this->getUser()->getId() . '');
$su->setUser($user);
$su->setDateCreate(new \DateTime());
$em->persist($su);
$em->flush();
$this->addFlash('su_alert_success', "Le site " . $su->getSite()->getLabel() . " affecté avec succès");
return $this->redirectToRoute('app_user_view', [
'user_id' => $user->getId(),
]);
}
}
return $this->render('security/view.html.twig', [
'user' => $user,
'sus' => $sus,
'suForm' => $suForm->createView(),
]);
}
public function suRemove(Request $request)
{
$su = $this->registry->getRepository(SiteUser::class)->findOneBy([
'id' => $request->get('su_id'),
//'isDeleted' => false,
]);
if ($su === null) {
$this->addFlash('not_found_user', 'Le compte utilisateur ' . ucfirst($request->get('user_id')) . ' n\'a pas été trouvé');
return $this->redirectToRoute('app_user_register');
}
$em = $this->registry->getManager();
$su->setIsDeleted(true);
$em->persist($su);
$em->flush();
$this->addFlash('su_alert_success', "Le site " . $su->getSite()->getLabel() . " retiré avec succès");
return $this->redirectToRoute('app_user_view', [
'user_id' => $su->getUser()->getId(),
]);
}
public function profil(Request $request, UserPasswordHasherInterface $passwordHasher)
{
$user = $this->getUser();
$form = $this->createForm(ProfilFormType::class, $user);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$user->setPassword(
$passwordHasher->hashPassword(
$user,
$form->get('password')->getData()
)
);
$user->setUpdatePasswordDate(new \DateTime());
$em = $this->registry->getManager();
$em->persist($user);
$em->flush();
$this->addFlash('update_profil_success', 'Votre profil a été modifié avec succès!');
return $this->redirectToRoute('app_user_profil');
}
return $this->render('security/profil.html.twig', [
'user' => $user,
'profilForm' => $form->createView(),
]);
}
public function register(Request $request)
{
if ($this->getUser()->getUserType() != 6) {
$this->addFlash('workspace_alert_warning', "Vous ne pouvez pas accéder à la ressource sollicitée");
return $this->redirectToRoute('app_core_workspace');
}
$users = [];
$user = $this->getUser();
if ($user->getUserType() == 6) {
$users = $this->registry->getRepository(Users::class)->findAgent();
} else {
$users = $this->registry->getRepository(Users::class)->findAgentBySite($user->getSite()->getId());
}
$roles = [];
//$roles[] = ['id' => 6, 'label' => "SUPER ADMINISTRATEUR"];
$roles[] = ['id' => 1, 'label' => "ADMINISTRATEUR"];
$roles[] = ['id' => 8, 'label' => "SUPERVISEUR"];
$roles[] = ['id' => 2, 'label' => "AUTORITE DU SITE"];
$roles[] = ['id' => 5, 'label' => "VALIDATEUR DU SITE"];
$roles[] = ['id' => 7, 'label' => "RAPPORT OPS"];
$roles[] = ['id' => 3, 'label' => "OPERATEUR DE SAISI"];
$roles[] = ['id' => 4, 'label' => "INTERNAUTE"];
return $this->render('security/register.html.twig', [
'users' => $users,
'roles' => $roles,
]);
}
public function registerSurfer()
{
if ($this->getUser()->getUserType() != 6) {
$this->addFlash('workspace_alert_warning', "Vous ne pouvez pas accéder à la ressource sollicitée");
return $this->redirectToRoute('app_core_workspace');
}
$users = [];
$user = $this->getUser();
if ($user->getUserType() == 6) {
$users = $this->em->getRepository(Users::class)->findUsersByStatusCustomer();
}
return $this->render('security/register_surfer.html.twig', [
'users' => $users,
]);
}
public function setStatus(Request $request)
{
$user = $this->registry->getRepository(Users::class)->findOneBy([
'id' => $request->get('user_id'),
//'isDeleted' => false,
]);
if ($user === null) {
$this->addFlash('not_found_user', 'Le compte utilisateur ' . ucfirst($request->get('user_id')) . ' n\'a pas été trouvé');
return $this->redirectToRoute('app_user_register');
}
if ($user->getStatus()) {
$user->setStatus(false);
} else {
$user->setStatus(true);
}
$em = $this->registry->getManager();
$em->persist($user);
$em->flush();
if ($user->getStatus()) {
$this->addFlash('update_user_success', 'Compte utilisateur activé avec succès !');
} else {
$this->addFlash('update_user_success', 'Compte utilisateur désactivé avec succès !');
}
return $this->redirectToRoute('app_user_register');
}
public function goodbye(TokenStorageInterface $tokenStorage): Response
{
LogManager::save("inconnu", "Déconnexion réussie");
if ($this->getUser() instanceof UserInterface) {
// Déconnectez l'utilisateur en supprimant le token
$tokenStorage->setToken(null);
}
return $this->render('security/logout-goodbye.html.twig');
}
public function getTokenCsrf(CsrfTokenManagerInterface $csrfTokenManager): JsonResponse
{
$envCsrfToken = $this->getParameter('app_csrf_token');
$token = $csrfTokenManager->getToken($envCsrfToken);
return new JsonResponse(array(
"token" => $token->getValue()
));
}
}