src/Controller/AccountController.php line 319
<?php
namespace App\Controller;
use App\Entity\User;
use App\Utils\Utils;
use App\Entity\Mobile;
use Psr\Log\LoggerInterface;
use App\Entity\PasswordUpdate;
use App\Entity\UserInfoPlus;
use App\Form\PasswordUpdateType;
use Symfony\Component\Mime\Email;
use App\Repository\UserRepository;
use Symfony\Component\Form\FormError;
use App\Repository\InvitationRepository;
use App\Repository\UserInfoPlusRepository;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bridge\Doctrine\Types\UuidType;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\JsonResponse;
use Doctrine\DBAL\Exception\UniqueConstraintViolationException;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
class AccountController extends AbstractController
{
const TYPE_ACTEURS = [
1 => ["name" => 'un Producteur/Acheteur', "role" => "ROLE_PRODUCTEUR"],
2 => ["name" => 'un Agrégateur', "role" => "ROLE_AGREGATEUR"],
3 => ["name" => 'une Banque', "role" => "ROLE_BANQUE"],
4 => ["name" => 'un Assureur', "role" => "ROLE_ASSUREUR"],
6 => ["name" => 'un Exportateur', "role" => "ROLE_EXPORTATEUR"],
5 => ["name" => 'un DPV', "role" => "ROLE_DPV"],
];
const STATUT_JURIDIQUE = [
1 => 'GIE',
2 => 'Association',
3 => 'Coopérative',
4 => 'SARL',
5 => 'SA',
7 => 'Particulier',
// 6 => 'Autres',
];
const ACTIVITES = [
'01' => 'Oignon',
'02' => 'Tomate',
'03' => 'Gombo',
'11' => 'Mil',
'12' => 'Mais',
'13' => 'Sasame',
'14' => 'Riz',
'20' => 'Mangue',
'21' => 'Anacarde',
'22' => 'Citron',
'23' => 'Orange',
'24' => 'Pamplemousse'
];
const COUNTRIES = [
'AF' => ["name" => 'Afghanistan'],
'AX' => ["name" => 'Åland Islands'],
'AL' => ["name" => 'Albania'],
'DZ' => ["name" => 'Algeria'],
'AS' => ["name" => 'American Samoa'],
'AD' => ["name" => 'AndorrA'],
'AO' => ["name" => 'Angola'],
'AI' => ["name" => 'Anguilla'],
'AQ' => ["name" => 'Antarctica'],
'AG' => ["name" => 'Antigua and Barbuda'],
'AR' => ["name" => 'Argentina'],
'AM' => ["name" => 'Armenia'],
'AW' => ["name" => 'Aruba'],
'AU' => ["name" => 'Australia'],
'AT' => ["name" => 'Austria'],
'AZ' => ["name" => 'Azerbaijan'],
'BS' => ["name" => 'Bahamas'],
'BH' => ["name" => 'Bahrain'],
'BD' => ["name" => 'Bangladesh'],
'BB' => ["name" => 'Barbados'],
'BY' => ["name" => 'Belarus'],
'BE' => ["name" => 'Belgium'],
'BZ' => ["name" => 'Belize'],
'BJ' => ["name" => 'Benin'],
'BM' => ["name" => 'Bermuda'],
'BT' => ["name" => 'Bhutan'],
'BO' => ["name" => 'Bolivia'],
'BA' => ["name" => 'Bosnia and Herzegovina'],
'BW' => ["name" => 'Botswana'],
'BV' => ["name" => 'Bouvet Island'],
'BR' => ["name" => 'Brazil'],
'IO' => ["name" => 'British Indian Ocean Territory'],
'BN' => ["name" => 'Brunei Darussalam'],
'BG' => ["name" => 'Bulgaria'],
'BF' => ["name" => 'Burkina Faso'],
'BI' => ["name" => 'Burundi'],
'KH' => ["name" => 'Cambodia'],
'CM' => ["name" => 'Cameroon'],
'CA' => ["name" => 'Canada'],
'CV' => ["name" => 'Cape Verde'],
'KY' => ["name" => 'Cayman Islands'],
'CF' => ["name" => 'Central African Republic'],
'TD' => ["name" => 'Chad'],
'CL' => ["name" => 'Chile'],
'CN' => ["name" => 'China'],
'CX' => ["name" => 'Christmas Island'],
'CC' => ["name" => 'Cocos (Keeling) Islands'],
'CO' => ["name" => 'Colombia'],
'KM' => ["name" => 'Comoros'],
'CG' => ["name" => 'Congo'],
'CD' => ["name" => 'Congo, The Democratic Republic of the'],
'CK' => ["name" => 'Cook Islands'],
'CR' => ["name" => 'Costa Rica'],
'CI' => ["name" => 'Cote D\'Ivoire'],
'HR' => ["name" => 'Croatia'],
'CU' => ["name" => 'Cuba'],
'CY' => ["name" => 'Cyprus'],
'CZ' => ["name" => 'Czech Republic'],
'DK' => ["name" => 'Denmark'],
'DJ' => ["name" => 'Djibouti'],
'DM' => ["name" => 'Dominica'],
'DO' => ["name" => 'Dominican Republic'],
'EC' => ["name" => 'Ecuador'],
'EG' => ["name" => 'Egypt'],
'SV' => ["name" => 'El Salvador'],
'GQ' => ["name" => 'Equatorial Guinea'],
'ER' => ["name" => 'Eritrea'],
'EE' => ["name" => 'Estonia'],
'ET' => ["name" => 'Ethiopia'],
'FK' => ["name" => 'Falkland Islands (Malvinas)'],
'FO' => ["name" => 'Faroe Islands'],
'FJ' => ["name" => 'Fiji'],
'FI' => ["name" => 'Finland'],
'FR' => ["name" => 'France'],
'GF' => ["name" => 'French Guiana'],
'PF' => ["name" => 'French Polynesia'],
'TF' => ["name" => 'French Southern Territories'],
'GA' => ["name" => 'Gabon'],
'GM' => ["name" => 'Gambia'],
'GE' => ["name" => 'Georgia'],
'DE' => ["name" => 'Germany'],
'GH' => ["name" => 'Ghana'],
'GI' => ["name" => 'Gibraltar'],
'GR' => ["name" => 'Greece'],
'GL' => ["name" => 'Greenland'],
'GD' => ["name" => 'Grenada'],
'GP' => ["name" => 'Guadeloupe'],
'GU' => ["name" => 'Guam'],
'GT' => ["name" => 'Guatemala'],
'GG' => ["name" => 'Guernsey'],
'GN' => ["name" => 'Guinea'],
'GW' => ["name" => 'Guinea-Bissau'],
'GY' => ["name" => 'Guyana'],
'HT' => ["name" => 'Haiti'],
'HM' => ["name" => 'Heard Island and Mcdonald Islands'],
'VA' => ["name" => 'Holy See (Vatican City State)'],
'HN' => ["name" => 'Honduras'],
'HK' => ["name" => 'Hong Kong'],
'HU' => ["name" => 'Hungary'],
'IS' => ["name" => 'Iceland'],
'IN' => ["name" => 'India'],
'ID' => ["name" => 'Indonesia'],
'IR' => ["name" => 'Iran, Islamic Republic Of'],
'IQ' => ["name" => 'Iraq'],
'IE' => ["name" => 'Ireland'],
'IM' => ["name" => 'Isle of Man'],
'IL' => ["name" => 'Israel'],
'IT' => ["name" => 'Italy'],
'JM' => ["name" => 'Jamaica'],
'JP' => ["name" => 'Japan'],
'JE' => ["name" => 'Jersey'],
'JO' => ["name" => 'Jordan'],
'KZ' => ["name" => 'Kazakhstan'],
'KE' => ["name" => 'Kenya'],
'KI' => ["name" => 'Kiribati'],
'KP' => ["name" => 'Korea, Democratic People\'S Republic of'],
'KR' => ["name" => 'Korea, Republic of'],
'KW' => ["name" => 'Kuwait'],
'KG' => ["name" => 'Kyrgyzstan'],
'LA' => ["name" => 'Lao People\'S Democratic Republic'],
'LV' => ["name" => 'Latvia'],
'LB' => ["name" => 'Lebanon'],
'LS' => ["name" => 'Lesotho'],
'LR' => ["name" => 'Liberia'],
'LY' => ["name" => 'Libyan Arab Jamahiriya'],
'LI' => ["name" => 'Liechtenstein'],
'LT' => ["name" => 'Lithuania'],
'LU' => ["name" => 'Luxembourg'],
'MO' => ["name" => 'Macao'],
'MK' => ["name" => 'Macedonia, The Former Yugoslav Republic of'],
'MG' => ["name" => 'Madagascar'],
'MW' => ["name" => 'Malawi'],
'MY' => ["name" => 'Malaysia'],
'MV' => ["name" => 'Maldives'],
'ML' => ["name" => 'Mali'],
'MT' => ["name" => 'Malta'],
'MH' => ["name" => 'Marshall Islands'],
'MQ' => ["name" => 'Martinique'],
'MR' => ["name" => 'Mauritania'],
'MU' => ["name" => 'Mauritius'],
'YT' => ["name" => 'Mayotte'],
'MX' => ["name" => 'Mexico'],
'FM' => ["name" => 'Micronesia, Federated States of'],
'MD' => ["name" => 'Moldova, Republic of'],
'MC' => ["name" => 'Monaco'],
'MN' => ["name" => 'Mongolia'],
'MS' => ["name" => 'Montserrat'],
'MA' => ["name" => 'Morocco'],
'MZ' => ["name" => 'Mozambique'],
'MM' => ["name" => 'Myanmar'],
'NA' => ["name" => 'Namibia'],
'NR' => ["name" => 'Nauru'],
'NP' => ["name" => 'Nepal'],
'NL' => ["name" => 'Netherlands'],
'AN' => ["name" => 'Netherlands Antilles'],
'NC' => ["name" => 'New Caledonia'],
'NZ' => ["name" => 'New Zealand'],
'NI' => ["name" => 'Nicaragua'],
'NE' => ["name" => 'Niger'],
'NG' => ["name" => 'Nigeria'],
'NU' => ["name" => 'Niue'],
'NF' => ["name" => 'Norfolk Island'],
'MP' => ["name" => 'Northern Mariana Islands'],
'NO' => ["name" => 'Norway'],
'OM' => ["name" => 'Oman'],
'PK' => ["name" => 'Pakistan'],
'PW' => ["name" => 'Palau'],
'PS' => ["name" => 'Palestinian Territory, Occupied'],
'PA' => ["name" => 'Panama'],
'PG' => ["name" => 'Papua New Guinea'],
'PY' => ["name" => 'Paraguay'],
'PE' => ["name" => 'Peru'],
'PH' => ["name" => 'Philippines'],
'PN' => ["name" => 'Pitcairn'],
'PL' => ["name" => 'Poland'],
'PT' => ["name" => 'Portugal'],
'PR' => ["name" => 'Puerto Rico'],
'QA' => ["name" => 'Qatar'],
'RE' => ["name" => 'Reunion'],
'RO' => ["name" => 'Romania'],
'RU' => ["name" => 'Russian Federation'],
'RW' => ["name" => 'RWANDA'],
'SH' => ["name" => 'Saint Helena'],
'KN' => ["name" => 'Saint Kitts and Nevis'],
'LC' => ["name" => 'Saint Lucia'],
'PM' => ["name" => 'Saint Pierre and Miquelon'],
'VC' => ["name" => 'Saint Vincent and the Grenadines'],
'WS' => ["name" => 'Samoa'],
'SM' => ["name" => 'San Marino'],
'ST' => ["name" => 'Sao Tome and Principe'],
'SA' => ["name" => 'Saudi Arabia'],
'SN' => ["name" => 'Senegal'],
'CS' => ["name" => 'Serbia and Montenegro'],
'SC' => ["name" => 'Seychelles'],
'SL' => ["name" => 'Sierra Leone'],
'SG' => ["name" => 'Singapore'],
'SK' => ["name" => 'Slovakia'],
'SI' => ["name" => 'Slovenia'],
'SB' => ["name" => 'Solomon Islands'],
'SO' => ["name" => 'Somalia'],
'ZA' => ["name" => 'South Africa'],
'GS' => ["name" => 'South Georgia and the South Sandwich Islands'],
'ES' => ["name" => 'Spain'],
'LK' => ["name" => 'Sri Lanka'],
'SD' => ["name" => 'Sudan'],
'SR' => ["name" => 'Suriname'],
'SJ' => ["name" => 'Svalbard and Jan Mayen'],
'SZ' => ["name" => 'Swaziland'],
'SE' => ["name" => 'Sweden'],
'CH' => ["name" => 'Switzerland'],
'SY' => ["name" => 'Syrian Arab Republic'],
'TW' => ["name" => 'Taiwan, Province of China'],
'TJ' => ["name" => 'Tajikistan'],
'TZ' => ["name" => 'Tanzania, United Republic of'],
'TH' => ["name" => 'Thailand'],
'TL' => ["name" => 'Timor-Leste'],
'TG' => ["name" => 'Togo'],
'TK' => ["name" => 'Tokelau'],
'TO' => ["name" => 'Tonga'],
'TT' => ["name" => 'Trinidad and Tobago'],
'TN' => ["name" => 'Tunisia'],
'TR' => ["name" => 'Turkey'],
'TM' => ["name" => 'Turkmenistan'],
'TC' => ["name" => 'Turks and Caicos Islands'],
'TV' => ["name" => 'Tuvalu'],
'UG' => ["name" => 'Uganda'],
'UA' => ["name" => 'Ukraine'],
'AE' => ["name" => 'United Arab Emirates'],
'GB' => ["name" => 'United Kingdom'],
'US' => ["name" => 'United States'],
'UM' => ["name" => 'United States Minor Outlying Islands'],
'UY' => ["name" => 'Uruguay'],
'UZ' => ["name" => 'Uzbekistan'],
'VU' => ["name" => 'Vanuatu'],
'VE' => ["name" => 'Venezuela'],
'VN' => ["name" => 'Viet Nam'],
'VG' => ["name" => 'Virgin Islands, British'],
'VI' => ["name" => 'Virgin Islands, U.S.'],
'WF' => ["name" => 'Wallis and Futuna'],
'EH' => ["name" => 'Western Sahara'],
'YE' => ["name" => 'Yemen'],
'ZM' => ["name" => 'Zambia'],
'ZW' => ["name" => 'Zimbabwe']
];
#[Route('/login_check', name: 'app_login')]
public function login(AuthenticationUtils $authenticationUtils, Request $request): Response
{
$error = $authenticationUtils->getLastAuthenticationError();
$request->getSession('session')->getFlashBag()->clear();
$flashBag = $request->getSession('session')->getFlashBag();
if ($error) {
$flashBag->set('danger', $error->getMessageKey());
}
return $this->redirectToRoute('login_view');
}
#[Route('/login', name: 'login_view')]
public function loginViewlogin(AuthenticationUtils $authenticationUtils, Request $request): Response
{
// get the login error if there is one
$error = $authenticationUtils->getLastAuthenticationError();
// last username entered by the user
$lastUsername = $authenticationUtils->getLastUsername();
return $this->render('account/login.html.twig', [
'last_username' => $lastUsername,
'error' => $error,
]);
}
#[Route('/logout', name: 'app_logout')]
public function logout(Request $request, Response $response, TokenInterface $token): Response
{
$request->getSession()->invalidate();
return $this->redirectToRoute('login_view');
}
#[Route('/signup', name: 'app_signup')]
public function registerView(): Response
{
return $this->render('account/register.html.twig', [
'countries' => self::COUNTRIES,
'acteurs' => self::TYPE_ACTEURS,
'activites' => self::ACTIVITES,
'statutJuridiques' => self::STATUT_JURIDIQUE,
]);
}
#[Route('/register', name: 'app_register', methods: ['POST'])]
public function register(
Request $request,
EntityManagerInterface $entityManager,
UserRepository $usersRepo,
UserPasswordHasherInterface $userPasswordHasher,
LoggerInterface $logger,
MailerInterface $mailer,
UserRepository $userRepository,
string $mail_sender
): JsonResponse {
set_time_limit(0);
$newUser = new User();
// return $this->json(uniqid());
try {
$entityManager->getConnection()->beginTransaction();
// $code = strtoupper(Utils::generateUniqCod($usersRepo, 4));
$companyCode = $userRepository->findLastOrganizationCode();
if ($companyCode == null) {
$newUser->setCode('AAA');
} else {
$code = Utils::getCompanyCode($companyCode);
$newUser->setCode($code);
}
$newUser
->setIsValid(0)
->setCreatedAt(new \DateTime())
->setUpdatedAt(new \DateTime())
->setUuid(Utils::generateCaseID())
->setCountry($request->get('country'))
->setIdentification($request->get('identification'))
->setLegalStatus($request->get('statut'))
->setDomainActivity(empty($request->get('domaines')) > 0 ? [] : $request->get('domaines'))
->setFirstName($request->get('firstName'))
->setLastName($request->get('lastName'))
->setSociety($request->get('raisonsociale'))
->setPhone($request->get('phone'))
->setCaptcha(uniqid());
$randomPassword = $request->get('password');
$hashPassword = $userPasswordHasher->hashPassword($newUser, $randomPassword);
$newUser->setEmail($request->get('email'))
->setPassword($hashPassword)
->setRoles(array(self::TYPE_ACTEURS[$request->get('identification')]['role']))
->setIsActive(0)
->setIsSendMail(0)
// ->setCode($code)
->setCaptcha(sha1($companyCode));
if ($newUser->getEmail() != NULL) {
$email_validation_regex = "/^[a-z0-9!#$%&'*+\\/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+\\/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/";
if (0 == preg_match($email_validation_regex, $newUser->getEmail())) { // returns 1
return new JsonResponse(["err" => 'Email est incorrect'], 500);
}
}
$entityManager->persist($newUser);
$entityManager->flush();
$entityManager->getConnection()->commit();
try {
$fullName = $newUser->getSociety() . $newUser->getFirstName() . ' ' . $newUser->getLastName();
$telephone = $newUser->getPhone();
$codeCompany = $newUser->getCode();
$email = (new Email())
// ->from('sysagri@statinfo.sn')
->from("$mail_sender")
->to('btamba@statinfo.sn')
->addTo('tcissokho@statinfo.sn')
->addTo('bounafode@gmail.com')
->subject('Notification compte')
->html("<p>Bonjour,</p>
<p>$fullName s'est inscrit sur la plateforme SysAgri et son code organisation est <b>$codeCompany</b></p>
<p>Veuillez le contactez sur ce numéro <b>$telephone</b> !</p>");
$mailer->send($email);
} catch (\Exception $th) {
//throw $th;
}
} catch (UniqueConstraintViolationException $e) {
$entityManager->getConnection()->rollBack();
$isLoginDuplicate = $usersRepo->isDuplicated($newUser->getEmail());
if ($isLoginDuplicate) {
$mail = $newUser->getEmail();
return new JsonResponse(['err' => "cet adresse email $mail est déjà utilisé !"], 500);
}
} catch (\Exception $e) {
$entityManager->getConnection()->rollBack();
return new JsonResponse(['err' => $e->getMessage()], 500);
} finally {
$logger->info(json_encode($newUser));
}
return new JsonResponse($newUser, 200);
}
#[Route('/users/sendMail', name: 'app_acount_sendMail')]
#[IsGranted('ROLE_USER')]
public function sendMailForWebUser(
MailerInterface $mailer,
Request $request,
UserRepository $repo,
EntityManagerInterface $entityManager,
string $mail_sender
): JsonResponse {
ini_set('memory_limit', '4096M');
set_time_limit(0);
$status = $request->get('status');
$code = substr($request->get('code'), 2, 3);
try {
$entityManager->getConnection()->beginTransaction();
$user = $repo->findOneBy(['code' => $code]);
if ($user && !$user->isIsSendMail()) {
// $user->setIsSendMail($status);
$fullName = $user->getSociety() . $user->getFirstName() . ' ' . $user->getLastName();
$lien = $request->getSchemeAndHttpHost() . $request->getBaseUrl() . $this->generateUrl('app_opened_email', ['captcha' => $user->getCaptcha()]); //"http://41.214.64.148/pigor_denombrement/public/index.php/candidatures/pieceJointes/" . $candidat->getNumeroDossier();
$companyCode = $request->get('code');
$email = (new Email())
// ->from('rgph5ansd@gmail.com')
->from("$mail_sender")
->to($user->getEmail())
->subject('Confirmation compte')
->html("<p>Bonjour $fullName,</p>
<p>Le code de votre organisation est <b>$companyCode</b></p>
<p>vous vous êtes inscrit sur la plateforme <b>SysAgri Système</b>, veuillez confirmer en cliquant sur le lien ci-dessous <br/>
<a href='$lien' >$lien</a>
</p>");
$mailer->send($email);
$user->setIsSendMail(true)
->setIsUserConfirmEmail(false);
$entityManager->persist($user);
$entityManager->flush();
$entityManager->getConnection()->commit();
} else {
return $this->json("An email is already sended");
}
} catch (\Throwable $th) {
$entityManager->getConnection()->rollBack();
return new JsonResponse($th->getMessage(), 500);
}
return new JsonResponse('Mail sended successfully !', 200);
}
// Permet d'ouvrir le formulaire simplifié d'enregistrement pour un invité
#[Route('/invitation/register/{token}', name: 'app_account_invitation_register', options: ['expose' => true])]
public function simpleRegister($token, InvitationRepository $repo): Response
{
$invited = $repo->findOneBy(['token' => $token]);
return $this->render('account/register-invited.html.twig', ['invitation' => $invited]);
}
#[Route('/invitedregister', name: 'app_invitation_register', methods: ['POST'])]
public function invitationRegister(
Request $request,
EntityManagerInterface $entityManager,
UserRepository $usersRepo,
UserPasswordHasherInterface $userPasswordHasher,
LoggerInterface $logger
): JsonResponse {
set_time_limit(0);
$newUser = new User();
try {
$organisation = $usersRepo->findOneBy(["id" => $request->get("token")]);
$orgaName = $organisation->getSociety() != NULL
? $organisation->getSociety()
: $organisation->getFirstName() . " " . $organisation->getLastName();
$entityManager->getConnection()->beginTransaction();
$code = strtoupper(Utils::generateUniqCod($usersRepo, 4));
$newUser
->setCreatedAt(new \DateTime())
->setUuid(uniqid())
->setCountry($organisation->getCountry())
->setIdentification($organisation->getIdentification())
->setLegalStatus($organisation->getLegalStatus())
->setDomainActivity($organisation->getDomainActivity())
->setFirstName($request->get('firstName'))
->setLastName($request->get('lastName'))
->setSociety($orgaName)
->setPhone($request->get('phone'))
->setCaptcha(uniqid());
$randomPassword = $request->get('password');
$hashPassword = $userPasswordHasher->hashPassword($newUser, $randomPassword);
$newUser->setEmail($request->get('email'))
->setPassword($hashPassword)
->setRoles($organisation->getRoles())
->setIsSendMail(1)
->setIsUserConfirmEmail(1)
->setIsActive(1)
->setIsValid(1)
->setCode($code)
->setCaptcha(Utils::customUuid(32))
->setParentCode($organisation->getCode())
->setLangue($organisation->getLangue());
if ($newUser->getEmail() != NULL) {
$email_validation_regex = "/^[a-z0-9!#$%&'*+\\/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+\\/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/";
if (0 == preg_match($email_validation_regex, $newUser->getEmail())) { // returns 1
return new JsonResponse(["err" => 'Email est incorrect'], 500);
}
}
$entityManager->persist($newUser);
$entityManager->flush();
$entityManager->getConnection()->commit();
} catch (UniqueConstraintViolationException $e) {
$entityManager->getConnection()->rollBack();
$isLoginDuplicate = $usersRepo->isDuplicated($newUser->getEmail());
if ($isLoginDuplicate) {
$mail = $newUser->getEmail();
return new JsonResponse(['err' => "cet adresse email $mail est déjà utilisé !"], 500);
}
} catch (\Exception $e) {
$entityManager->getConnection()->rollBack();
return new JsonResponse(['err' => $e->getMessage()], 500);
} finally {
$logger->info(json_encode($newUser));
}
$this->addFlash(
'success',
'Vous venez de créer votre compte avec succès, veuillez-vous connecter !'
);
return new JsonResponse($newUser, 200);
}
#[Route('/forgot-password', name: 'app_forgot_password')]
public function forgotPassword(
Request $request,
UserRepository $userRepository,
EntityManagerInterface $entityManager,
MailerInterface $mailer
): Response {
$request->getSession()->invalidate();
if ($request->getMethod() == "POST") {
try {
$entityManager->beginTransaction();
$token = Utils::customUuid(100);
$keyRecover = "S-" . Utils::generateRandomPassword(6);
$account = $userRepository->findOneBy(["email" => $request->get("email")]);
if ($account == NULL) {
$this->addFlash(
'danger',
"Aucun compte n'a été enregistré sous cette adresse email"
);
return $this->render('account/forgot-password.html.twig');
} else if (count($account->getUserInfoPluses()) > 0) {
$newRecover = $account->getUserInfoPluses()[0];
$newRecover
->setSentAt(new \DateTime())
->setIsPasswordChanged(false)
->setKeyRecover($keyRecover)
->setToken($token);
$entityManager->persist($newRecover);
$entityManager->flush();
$entityManager->commit();
$this->addFlash(
'success',
"Un email vous a été envoyé pour réinitialiser votre mot de passe et expire dans 15 minutes."
);
} else {
$newRecover = new UserInfoPlus();
$newRecover
->setUtilisateur($account)
->setSentAt(new \DateTime())
->setIsPasswordChanged(false)
->setKeyRecover($keyRecover)
->setToken($token);
$entityManager->persist($newRecover);
$entityManager->flush();
$entityManager->commit();
$this->addFlash(
'success',
"Un email vous a été envoyé pour réinitialiser votre mot de passe."
);
}
// if (count($account->getUserInfoPluses()) > 0) {
try {
$fullName = $account->getSociety() . " " . $account->getFirstName() . ' ' . $account->getLastName();
$lien = $request->getSchemeAndHttpHost() . $request->getBaseUrl() . $this->generateUrl('app_forgot_password_recover', ['token' => $token]); //"http://41.214.64.148/pigor_denombrement/public/index.php/candidatures/pieceJointes/" . $candidat->getNumeroDossier();
$email = (new Email())
->from('sysagri@statinfo.sn')
->to($account->getEmail())
->subject('Password recover')
->html("<p>Bonjour $fullName,</p>
<p>Votre code de réinitialisation est <b>$keyRecover</b>. Click sur le lien ci-dessous pour changer votre mot de passe.</p>
<p><a href='$lien' >$lien</a></p>");
$mailer->send($email);
} catch (\Throwable $th) {
throw $th;
}
// }
} catch (\Exception $th) {
//throw $th;
$entityManager->rollback();
$this->addFlash(
'danger',
$th->getMessage()
);
}
}
return $this->render('account/forgot-password.html.twig');
}
#[Route('/recover-password/{token}/recover', name: 'app_forgot_password_recover', options: ['expose' => true])]
public function forgotPasswordChanged(
$token,
Request $request,
UserInfoPlusRepository $repo,
EntityManagerInterface $entityManager,
UserPasswordHasherInterface $userPasswordHasher
): Response {
$expiredTokenMin = $this->getParameter("expiredTokenMin");
$recoverPassword = $repo->findOneBy(['token' => $token]);
$isValideToken = false;
if ($recoverPassword == NULL) {
$this->addFlash(
'danger',
"Token invalide"
);
} else {
if ($recoverPassword->isIsPasswordChanged()) {
$this->addFlash(
'danger',
"Un changement de mot de passe a déjà été effectué avec ce token."
);
return $this->render('account/recover-password.html.twig', ['isValidToken' => $isValideToken, 'token' => $token]);
}
$isExipredToken = Utils::isExpireDate($recoverPassword->getSentAt(), $expiredTokenMin);
if ($isExipredToken) {
$this->addFlash(
'danger',
"Token expiré, Merci de réinitialiser votre compte à nouveau !"
);
} else {
$isValideToken = true;
}
}
try {
if ($request->getMethod() == "POST" && $isValideToken) {
$entityManager->beginTransaction();
$findRecoverPassword = $repo->findOneBy(['token' => $token, "keyRecover" => $request->get("codeValidation")]);
if ($findRecoverPassword == NULL) {
$this->addFlash(
'danger',
"Code invalide, merci de renseigner le code envoyé par E-mail"
);
} else {
$dt = new \DateTime();
$myAccount = $findRecoverPassword->getUtilisateur();
$randomPassword = $request->get('password');
$hashPassword = $userPasswordHasher->hashPassword($myAccount, $randomPassword);
$myAccount
->setPassword($hashPassword)
->setUpdatedAt($dt);
$entityManager->persist($myAccount);
$findRecoverPassword
->setIsPasswordChanged(true)
->setPasswordChangeAt($dt);
$entityManager->persist($findRecoverPassword);
$entityManager->flush();
$entityManager->commit();
$this->addFlash(
'success',
"Votre mot de passe a été changé avec succès !"
);
return $this->redirectToRoute('login_view');
}
}
} catch (\Exception $th) {
$entityManager->rollback();
$this->addFlash(
'danger',
$th->getMessage()
);
}
return $this->render('account/recover-password.html.twig', ['isValidToken' => $isValideToken, 'token' => $token]);
}
}