src/Controller/SecurityController.php line 89

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Constant\UserStatus;
  4. use App\Entity\User;
  5. use App\Services\HashGenerator;
  6. use App\Services\Mailer;
  7. use Doctrine\Persistence\ManagerRegistry;
  8. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  9. use Symfony\Component\HttpFoundation\Request;
  10. use Symfony\Component\HttpFoundation\Response;
  11. use Symfony\Component\Routing\Annotation\Route;
  12. use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
  13. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  14. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  15. class SecurityController extends AbstractController
  16. {
  17.     private $doctrine;
  18.     private $hashGenerator;
  19.     private $mailer;
  20.     private $passwordEncoder;
  21.     public function __construct(ManagerRegistry $doctrineHashGenerator $hashGeneratorMailer $mailerUserPasswordHasherInterface $passwordEncoder){
  22.         $this->doctrine $doctrine;
  23.         $this->hashGenerator $hashGenerator;
  24.         $this->mailer $mailer;
  25.         $this->passwordEncoder $passwordEncoder;
  26.     }
  27.     /**
  28.      * @Route("/", name="login")
  29.      */
  30.     public function login(AuthenticationUtils $authenticationUtils)
  31.     {
  32.         // redirect if already logged
  33.         if ($this->getUser()) {
  34.             $userRoles $this->getUser()->getRoles();
  35.             if (in_array("ROLE_SUPER_ADMIN"$userRoles) || in_array("ROLE_ADMIN"$userRoles)){
  36.                 return $this->redirectToRoute('admin_dashboard');
  37.             }
  38.             if (in_array("ROLE_PARTNER"$userRoles)){
  39.                 return $this->redirectToRoute('partner_dashboard');
  40.             }
  41.             if (in_array("ROLE_CUSTOMER"$userRoles)){
  42.                 return $this->redirectToRoute('account_projects', ['accountId' => $this->getUser()->getMembership()->getAccount()->getId()]);
  43.             }
  44.         }
  45.         $error $authenticationUtils->getLastAuthenticationError();
  46.         $lastEmail $authenticationUtils->getLastUsername();
  47.         return $this->render('security/login.html.twig', [
  48.             'title' => "Log in",
  49.             'last_email' => $lastEmail,
  50.             'error' => $error,
  51.             'type' => 'admin'
  52.         ]);
  53.     }
  54.     /**
  55.      * @Route("/logout", name="logout")
  56.      */
  57.     public function logout()
  58.     {
  59.     }
  60.     /**
  61.      * @Route("/access-denied", name="access_denied")
  62.      */
  63.     public function accessDenied(): Response {
  64.         return $this->render('security/access-denied.html.twig');
  65.     }
  66.     /**
  67.      * @Route("/forgot-password", name="forgot_password")
  68.      */
  69.     public function forgotPassword(): Response {
  70.         $error '';
  71.         $message '';
  72.         $email '';
  73.         if ($_POST) {
  74.             $email $_POST['email'];
  75.             $repository $this->doctrine->getRepository(User::class);
  76.             $user $repository->findOneBy(['email' => $_POST['email']]);
  77.             if ($user){
  78.                 $userStatus = new UserStatus();
  79.                 $statusSuspended $userStatus->getUserStatusId('Suspended');
  80.                 if ($user->getStatus() == $statusSuspended) {
  81.                     $error 'Your user account has been suspended.';
  82.                 } else {
  83.                     $lastTokenCreated $user->getTokenCreatedAt();
  84.                     $dateValid = (new \DateTime("now"))->modify('-1 hour');
  85.                     if ($lastTokenCreated && $lastTokenCreated $dateValid){
  86.                         $error 'We already received your request. Check your email or try again later.';
  87.                     } else {
  88.                         $token $this->hashGenerator->uuid4();
  89.                         $user->setToken($token);
  90.                         $user->setTokenCreatedAt(new \DateTime());
  91.                         $em $this->doctrine->getManager();
  92.                         $em->persist($user);
  93.                         $em->flush();
  94.                         $url $this->generateUrl('reset_password',
  95.                             array('token' => $token),
  96.                             UrlGeneratorInterface::ABSOLUTE_URL
  97.                         );
  98.                         $context = [
  99.                             'user_email' => $user->getEmail(),
  100.                             'url' => $url
  101.                         ];
  102.                         $to $user->getEmail();
  103.                         $subject 'Reset Your Password.';
  104.                         $type 'reset_password';
  105.                         $this->mailer->sendTemplatedMail($to$subject$type$context);
  106.                         $message 'Request for password reset sent successfully. Check your email for further instructions.';
  107.                         $email '';
  108.                     }
  109.                 }
  110.             } else {
  111.                 $error 'User not found';
  112.             }
  113.         }
  114.         return $this->render('security/forgot-password.html.twig', [
  115.             'title' => "Forgot password",
  116.             'last_email' => $email,
  117.             'error' => $error,
  118.             'message' => $message
  119.         ]);
  120.     }
  121.     /**
  122.      * @Route("/reset-password/{token}", name="reset_password")
  123.      */
  124.     public function resetPassword($token)
  125.     {
  126.         $error '';
  127.         $message '';
  128.         $repository $this->doctrine->getRepository(User::class);
  129.         $user $repository->findOneBy(['token' => $token]);
  130.         $userStatus = new UserStatus();
  131.         $statusSuspended $userStatus->getUserStatusId('Suspended');
  132.         if (!$user) {
  133.             $error 'Your request has been expired.';
  134.         } else if ($user->getStatus() == $statusSuspended) {
  135.             $error 'Your user account has been suspended.';
  136.         } else if ($_POST) {
  137.             $password trim($_POST['password']);
  138.             $password_retype trim($_POST['password_retype']);
  139.             $strength $this->hashGenerator->passwordStrengthCheck($password);
  140.             if(!$strength['valid']) {
  141.                 $error $strength['message'];
  142.             } else if ($password != $password_retype){
  143.                 $error "Retyped password doesn't match";
  144.             } else {
  145.                 $new_pwd_encoded $this->passwordEncoder->hashPassword($user$password);
  146.                 $currentStatus $user->getStatus();
  147.                 $statusPending $userStatus->getUserStatusId('Pending');
  148.                 $statusActive $userStatus->getUserStatusId('Active');
  149.                 if ($currentStatus == $statusPending){
  150.                     $user->setStatus($statusActive);
  151.                 }
  152.                 $user->setToken(null);
  153.                 $user->setTokenCreatedAt(null);
  154.                 $user->setPassword($new_pwd_encoded);
  155.                 $em $this->doctrine->getManager();
  156.                 $em->persist($user);
  157.                 $em->flush();
  158.                 $this->addFlash(
  159.                     'notice',
  160.                     'Your password has been changed.'
  161.                 );
  162.                 return $this->redirectToRoute('login');
  163.             }
  164.         }
  165.         return $this->render('security/reset-password.html.twig', [
  166.             'title' => "Reset password",
  167.             'token' => $token,
  168.             'error' => $error,
  169.             'message' => $message
  170.         ]);
  171.     }
  172.     /**
  173.      * @Route("/my-profile", name="my_profile")
  174.      */
  175.     public function myProfile(Request $request): Response {
  176.         $error false;
  177.         $passChanged false;
  178.         $message '';
  179.         if ($request->isMethod('post')) {
  180.             $user $this->getUser();
  181.             $firstName trim($request->get('firstName'));
  182.             $lastName trim($request->get('lastName'));
  183.             $password trim($request->get('password'));
  184.             $password_retype trim($request->get('password_retype'));
  185.             $infoChanged = ($firstName != $user->getFirstName() || $lastName != $user->getLastName());
  186.             if (strlen($firstName) < || strlen($lastName) < 2) {
  187.                 $error true;
  188.                 $message .= 'Your first name and last name should be at least 2 characters long<br>';
  189.             } else {
  190.                 $user->setFirstName($firstName);
  191.                 $user->setlastName($lastName);
  192.             }
  193.             if (strlen($password) > 0){
  194.                 $strength $this->hashGenerator->passwordStrengthCheck($password);
  195.                 if(!$strength['valid']) {
  196.                     $error true;
  197.                     $message .= $strength['message'].'<br>';
  198.                 } else if ($password != $password_retype){
  199.                     $error true;
  200.                     $message .= "Retyped password doesn't match<br>";
  201.                 } else {
  202.                     $new_pwd_encoded $this->passwordEncoder->hashPassword($user$password);
  203.                     $user->setPassword($new_pwd_encoded);
  204.                     $passChanged true;
  205.                 }
  206.             }
  207.             if ($error){
  208.                 $this->addFlash('error'$message);
  209.             } else {
  210.                 $em $this->doctrine->getManager();
  211.                 $em->persist($user);
  212.                 $em->flush();
  213.                 if ($infoChanged && $passChanged){
  214.                     $this->addFlash('notice''Your profile info and password successfully changed');
  215.                 } elseif ($infoChanged) {
  216.                     $this->addFlash('notice''Your profile info successfully changed');
  217.                 } elseif ($passChanged){
  218.                     $this->addFlash('notice''Your password successfully changed');
  219.                 } else {
  220.                     $this->addFlash('notice''Nothing changed');
  221.                 }
  222.             }
  223.         }
  224.         $appType '';
  225.         $account null;
  226.         $roles $this->getUser()->getRoles();
  227.         foreach ($roles as $role){
  228.             if ($role == "ROLE_ADMIN" || $role == "ROLE_SUPER_ADMIN" || $role == "ROLE_ADMIN_VIEWER"){
  229.                 $appType 'admin';
  230.             }
  231.             if ($role == "ROLE_PARTNER"){
  232.                 $appType 'partner';
  233.             }
  234.             if ($role == "ROLE_CUSTOMER"){
  235.                 $appType 'account';
  236.                 $account $this->getUser()->getMembership()->getAccount();
  237.             }
  238.         }
  239.         return $this->render('security/profile.html.twig', [
  240.             'app_type' => $appType,
  241.             'title' => 'My Profile',
  242.             'account' => $account,
  243.             'accountId' => ($account) ? $account->getId() : null,
  244.             'showPayment' => false,
  245.         ]);
  246.     }
  247. }