src/Security/UserAuthenticator.php line 27

Open in your IDE?
  1. <?php
  2. namespace App\Security;
  3. use App\Entity\ProjectMembers;
  4. use App\Entity\Project;
  5. use App\Entity\User;
  6. use App\Entity\Permission;
  7. use App\Entity\UserGroup;
  8. use Doctrine\ORM\EntityManagerInterface;
  9. use Symfony\Component\HttpFoundation\RedirectResponse;
  10. use Symfony\Component\HttpFoundation\Request;
  11. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  12. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  13. use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
  14. use Symfony\Component\Security\Core\Exception\CustomUserMessageAuthenticationException;
  15. use Symfony\Component\Security\Core\Exception\InvalidCsrfTokenException;
  16. use Symfony\Component\Security\Core\Security;
  17. use Symfony\Component\Security\Core\User\UserInterface;
  18. use Symfony\Component\Security\Core\User\UserProviderInterface;
  19. use Symfony\Component\Security\Csrf\CsrfToken;
  20. use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface;
  21. use Symfony\Component\Security\Guard\Authenticator\AbstractFormLoginAuthenticator;
  22. use Symfony\Component\Security\Guard\PasswordAuthenticatedInterface;
  23. use Symfony\Component\Security\Http\Util\TargetPathTrait;
  24. class UserAuthenticator extends AbstractFormLoginAuthenticator implements PasswordAuthenticatedInterface
  25. {
  26.     use TargetPathTrait;
  27.     private $entityManager;
  28.     private $urlGenerator;
  29.     private $csrfTokenManager;
  30.     private $passwordEncoder;
  31.     private $user;
  32.     public function __construct(EntityManagerInterface $entityManagerUrlGeneratorInterface $urlGeneratorCsrfTokenManagerInterface $csrfTokenManagerUserPasswordEncoderInterface $passwordEncoder)
  33.     {
  34.         $this->entityManager $entityManager;
  35.         $this->urlGenerator $urlGenerator;
  36.         $this->csrfTokenManager $csrfTokenManager;
  37.         $this->passwordEncoder $passwordEncoder;
  38.     }
  39.     public function supports(Request $request)
  40.     {
  41.         return 'app_login' === $request->attributes->get('_route')
  42.             && $request->isMethod('POST');
  43.     }
  44.     public function getCredentials(Request $request)
  45.     {
  46.         $credentials = [
  47.             'email' => $request->request->get('email'),
  48.             'password' => $request->request->get('password'),
  49.             'csrf_token' => $request->request->get('_csrf_token'),
  50.         ];
  51.         $request->getSession()->set(
  52.             Security::LAST_USERNAME,
  53.             $credentials['email']
  54.         );
  55.         return $credentials;
  56.     }
  57.     public function getUser($credentialsUserProviderInterface $userProvider)
  58.     {
  59.         $token = new CsrfToken('authenticate'$credentials['csrf_token']);
  60.         if (!$this->csrfTokenManager->isTokenValid($token)) {
  61.             throw new InvalidCsrfTokenException();
  62.         }
  63.         $user $this->entityManager->getRepository(User::class)->findOneBy(['email' => $credentials['email']]);
  64.         if (!$user) {
  65.             // fail authentication with a custom error
  66.             throw new CustomUserMessageAuthenticationException('Email could not be found.');
  67.         }
  68.         $this->user $user;
  69.         return $user;
  70.     }
  71.     public function checkCredentials($credentialsUserInterface $user)
  72.     {
  73.         return $this->passwordEncoder->isPasswordValid($user$credentials['password']);
  74.     }
  75.     /**
  76.      * Used to upgrade (rehash) the user's password automatically over time.
  77.      */
  78.     public function getPassword($credentials): ?string
  79.     {
  80.         return $credentials['password'];
  81.     }
  82.     public function onAuthenticationSuccess(Request $requestTokenInterface $token$providerKey)
  83.     {
  84.         $user $this->user;
  85.         $role $user->getRoles()[0];
  86.         if ($role === "ROLE_USER") {
  87.            /* if (!$user->getLastLogin()) {
  88.                 return new RedirectResponse($this->urlGenerator->generate('change_password'));
  89.             } elseif ($user->getIsActive() == false) {
  90.                 throw new CustomUserMessageAuthenticationException('Your account is temporarily inactive. Contact the system administrator');
  91.                 return new RedirectResponse('app_login');
  92.             }*/
  93.         }
  94.         $this->user->setLastLogin(new \DateTime());
  95.         $this->entityManager->flush();
  96.         $permissions = [];
  97.         if ($user->getId() == 1) {
  98.             $permission $this->entityManager->getRepository(Permission::class)->findAll();
  99.             foreach ($permission as $key => $value1) {
  100.                 $permissions[] = $value1->getCode();
  101.             }
  102.         } else {
  103.             $groups $this->user->getUserGroup();
  104.             foreach ($groups as $key => $value) {
  105.                 if (!$value->getIsActive()) {
  106.                     continue;
  107.                 }
  108.                 $permission $value->getPermission();
  109.                 foreach ($permission as $key => $value1) {
  110.                     $permissions[] = $value1->getCode();
  111.                 }
  112.             }
  113.         }
  114.         $request->getSession()->set(
  115.             "PERMISSION",
  116.             $permissions
  117.         );
  118.         $projectMembersRepository $this->entityManager->getRepository(ProjectMembers::class);
  119.         $projectRepository $this->entityManager->getRepository(Project::class);
  120.         $projectMember $projectMembersRepository->findBy(['user' => $user'status' => 1]);
  121.         $projects = [];
  122.         $project_list = [];
  123.         foreach ($projectMember as $member) {
  124.             $project $projectRepository->findOneBy(['id' => $member->getProject()->getId()]);
  125.             array_push($projects$project);
  126.         }
  127.         $managingProjects $projectRepository->findBy(['project_manager' => $user]);
  128.         foreach ($managingProjects as $projectr) {
  129.             array_push($projects$projectr);
  130.         }
  131.         foreach ($projects as $proj) {
  132.             if (!in_array($proj$project_list)) {
  133.                 $project_list[] = $proj;
  134.             }
  135.         }
  136.         $request->getSession()->set(
  137.             "myprojects",
  138.             $project_list
  139.         );
  140.         if ($targetPath $this->getTargetPath($request->getSession(), $providerKey)) {
  141.             return new RedirectResponse($targetPath);
  142.         }
  143.         return new RedirectResponse($this->urlGenerator->generate('dashboard'));
  144.         throw new \Exception('TODO: provide a valid redirect inside ' __FILE__);
  145.     }
  146.     protected function getLoginUrl()
  147.     {
  148.         // return $this->urlGenerator->generate(self::LOGIN_ROUTE);
  149.         return $this->urlGenerator->generate('app_login');
  150.     }
  151. }