src/Controller/Api/SecurityController.php line 125

Open in your IDE?
  1. <?php
  2. namespace App\Controller\Api;
  3. use App\Manager\UserRegisterManager;
  4. use App\Repository\OrganizationRepository;
  5. use App\Service\JWTService;
  6. use App\Utils\UserUtils;
  7. use Doctrine\ORM\EntityManagerInterface;
  8. use Evo\Infrastructure\MappingORM\Organization;
  9. use Evo\Infrastructure\MappingORM\User;
  10. use Lexik\Bundle\JWTAuthenticationBundle\Services\JWTTokenManagerInterface;
  11. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  12. use Symfony\Component\HttpFoundation\JsonResponse;
  13. use Symfony\Component\HttpFoundation\Request;
  14. use Symfony\Component\HttpFoundation\Response;
  15. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  16. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  17. use Symfony\Component\Routing\Annotation\Route;
  18. use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
  19. class SecurityController extends AbstractController
  20. {
  21.     private UserRegisterManager $userRegisterManager;
  22.     private EntityManagerInterface $entityManager;
  23.     private UserUtils $userUtils;
  24.     private JWTTokenManagerInterface $JWTTokenManager;
  25.     private UserPasswordEncoderInterface $passwordEncoder;
  26.     private SessionInterface $session;
  27.     private JWTService $jwtService;
  28.     public function __construct(
  29.         UserRegisterManager $userRegisterManager,
  30.         EntityManagerInterface $entityManager,
  31.         UserUtils $userUtils,
  32.         JWTTokenManagerInterface $JWTTokenManager,
  33.         UserPasswordEncoderInterface $passwordEncoder,
  34.         SessionInterface $session,
  35.         JWTService $jwtService
  36.     ) {
  37.         $this->userRegisterManager $userRegisterManager;
  38.         $this->entityManager $entityManager;
  39.         $this->userUtils $userUtils;
  40.         $this->JWTTokenManager $JWTTokenManager;
  41.         $this->passwordEncoder $passwordEncoder;
  42.         $this->session $session;
  43.         $this->jwtService $jwtService;
  44.     }
  45.     /**
  46.      * @Route("/invoicetoken-auth", methods={"POST"}, name="app_invoicetoken_auth")
  47.      *
  48.      * @throws \JsonException
  49.      */
  50.     public function authByInvoiceToken(Request $requestOrganizationRepository $organizationRepository): JsonResponse
  51.     {
  52.         $body json_decode($request->getContent(), true512JSON_THROW_ON_ERROR);
  53.         if (!array_key_exists('invoiceToken'$body)) {
  54.             return new JsonResponse(['error' => 'No "invoiceToken" provided'], Response::HTTP_BAD_REQUEST);
  55.         }
  56.         $organization $organizationRepository->findOneBy(['invoiceToken' => $body['invoiceToken']]);
  57.         if (!$organization instanceof Organization) {
  58.             return new JsonResponse(['error ' => 'Unknown token'], Response::HTTP_FORBIDDEN);
  59.         }
  60.         $firstUser $organization->getUsers()[0];
  61.         return new JsonResponse(['token' => $this->JWTTokenManager->create($firstUser)]);
  62.     }
  63.     /**
  64.      * @Route("/send-back-code", name="app_send_back_code", methods={"POST"})
  65.      */
  66.     public function sendBackCode(Request $request): JsonResponse
  67.     {
  68.         $query json_decode($request->getContent(), true512JSON_THROW_ON_ERROR);
  69.         if (empty($query['email'])) {
  70.             throw new NotFoundHttpException('Not found username in query to handle request new password');
  71.         }
  72.         $email $query['email'];
  73.         /** @var User $user */
  74.         $user $this->entityManager->getRepository(User::class)->loadUserByUsername($emailtrue);
  75.         if (null === $user) {
  76.             throw new NotFoundHttpException(sprintf('Not found user with username: "%s"'$email));
  77.         }
  78.         if ('admin@digidom.pro' === $user->getEmail()) {
  79.             return new JsonResponse('alert');
  80.         }
  81.         $code $this->userUtils->generateCodeConfirmation();
  82.         $user->setCodeConfirmation($code);
  83.         $this->entityManager->persist($user);
  84.         $this->entityManager->flush();
  85.         $this->session->set('current_user'serialize($user));
  86.         return new JsonResponse('success');
  87.     }
  88.     /**
  89.      * @Route("/request-new-pwd", methods={"POST"}, name="app_request_new_pwd")
  90.      */
  91.     public function requestNewPassword(Request $request): JsonResponse
  92.     {
  93.         $query json_decode($request->getContent(), true512JSON_THROW_ON_ERROR);
  94.         if (empty($query['username'])) {
  95.             throw new NotFoundHttpException('Not found username in query to handle request new password');
  96.         }
  97.         /** @var User $user */
  98.         $user $this->entityManager->getRepository(User::class)->loadUserByUsername($query['username'], true);
  99.         if (null === $user) {
  100.             throw new NotFoundHttpException(sprintf('Not found user with username: "%s"'$query['username']));
  101.         }
  102.         if ('admin@digidom.pro' === $user->getEmail()) {
  103.             return new JsonResponse('alert');
  104.         }
  105.         $user $this->userRegisterManager->initHashToken($user);
  106.         $this->entityManager->persist($user);
  107.         $this->entityManager->flush();
  108.         return new JsonResponse('success');
  109.     }
  110.     /**
  111.      * @Route("/login", name="app_user_login", methods={"POST"})
  112.      */
  113.     public function checkAuthentification(Request $request): JsonResponse
  114.     {
  115.         $query json_decode($request->getContent(), true512JSON_THROW_ON_ERROR);
  116.         if (empty($query['username']) || empty($query['password'])) {
  117.             return new JsonResponse(['code' => 404'message' => 'Undefined parameter code or username'], Response::HTTP_NOT_FOUND);
  118.         }
  119.         $email $query['username'];
  120.         $user $this->entityManager->getRepository(User::class)->loadUserByUsername($emailtrue);
  121.         if (null === $user) {
  122.             return new JsonResponse(['code' => 404'message' => 'User not found'], Response::HTTP_NOT_FOUND);
  123.         }
  124.         if (!$this->passwordEncoder->isPasswordValid($user$query['password'])) {
  125.             return new JsonResponse(['code' => 401'message' => 'Invalid credential'], Response::HTTP_UNAUTHORIZED);
  126.         }
  127.         $code $this->userUtils->generateCodeConfirmation();
  128.         $user->setCodeConfirmation($code);
  129.         $this->entityManager->persist($user);
  130.         $this->entityManager->flush();
  131.         return new JsonResponse(['roles' => $user->getRoles()]);
  132.     }
  133.     /**
  134.      * @Route("/check-code", name="app_user_check_code", methods={"POST"})
  135.      */
  136.     public function checkConfirmationCode(Request $request): JsonResponse
  137.     {
  138.         $query json_decode($request->getContent(), true512JSON_THROW_ON_ERROR);
  139.         if (empty($query['code']) || empty($query['username'])) {
  140.             return new JsonResponse(['code' => 404'message' => 'Undefined parameter code or username'], Response::HTTP_NOT_FOUND);
  141.         }
  142.         $username $query['username'];
  143.         /** @var User $user */
  144.         $user $this->entityManager->getRepository(User::class)->loadUserByUsername($usernametrue);
  145.         if (null === $user) {
  146.             return new JsonResponse(['code' => 404'message' => 'User not found'], Response::HTTP_NOT_FOUND);
  147.         }
  148.         if ($query['code'] != $user->getCodeConfirmation()) {
  149.             return new JsonResponse(['code' => 401'message' => 'Invalide code'], Response::HTTP_NOT_FOUND);
  150.         }
  151.         return new JsonResponse([
  152.             'id' => $user->getId(),
  153.             'email' => $user->getEmail(),
  154.             'lastname' => $user->getLastname(),
  155.             'firstname' => $user->getFirstname(),
  156.             'roles' => $user->getRoles(),
  157.             'phoneNumber' => $user->getPhoneNumber(),
  158.             'codeConfirmation' => $user->getCodeConfirmation(),
  159.         ]);
  160.     }
  161.     /**
  162.      * @Route("/change-password", name="app_user_change_password", methods={"POST"})
  163.      */
  164.     public function changePassword(Request $request): JsonResponse
  165.     {
  166.         $parameters json_decode($request->getContent(), true512JSON_THROW_ON_ERROR);
  167.         if (!array_key_exists('resetToken'$parameters) || empty($parameters['resetToken'])) {
  168.             return new JsonResponse(['error' => 'emptyResetToken']);
  169.         }
  170.         /** @var User $user */
  171.         $user $this->entityManager->getRepository(User::class)->findOneBy([
  172.             'resetToken' => $parameters['resetToken'],
  173.         ]);
  174.         if (!$user) {
  175.             return new JsonResponse(['error' => 'invalidToken']);
  176.         }
  177.         $userData = [
  178.             'email' => $user->getEmail(),
  179.             'id' => $user->getId(),
  180.         ];
  181.         if (time() > (int) $user->getResetTokenExpirationDate()) {
  182.             return new JsonResponse([
  183.                 'error' => 'tokenExpired',
  184.                 'user' => $userData,
  185.             ]);
  186.         }
  187.         if (!array_key_exists('password'$parameters) || empty($parameters['password'])) {
  188.             return new JsonResponse([
  189.                 'error' => 'emptyPassword',
  190.                 'user' => $userData,
  191.             ]);
  192.         }
  193.         if (!preg_match('/(?=^.{8,}$)((?=.*\d)|(?=.*\W+))(?![.\n])(?=.*[A-Z])(?=.*[a-z]).*$/',
  194.             $parameters['password'])) {
  195.             return new JsonResponse([
  196.                 'error' => 'incorrectPassword',
  197.                 'user' => $userData,
  198.             ]);
  199.         }
  200.         $user->setPassword($parameters['password']);
  201.         $user->setResetToken(null);
  202.         $user->setResetTokenExpirationDate(null);
  203.         $this->entityManager->flush();
  204.         return new JsonResponse([
  205.             'success' => true,
  206.             'user' => $userData,
  207.         ]);
  208.     }
  209.     /**
  210.      * @Route("/token-by-email", name="app_user_token_by_email", methods={"POST"})
  211.      */
  212.     public function tokenByEmail(Request $request)
  213.     {
  214.         $query json_decode($request->getContent(), true512JSON_THROW_ON_ERROR);
  215.         $email $query['email'];
  216.         $user $this->entityManager->getRepository(User::class)->findOneBy(['email' => $email]);
  217.         if (!$user instanceof User) {
  218.             return new JsonResponse(['code' => 404'message' => 'User not found'], Response::HTTP_NOT_FOUND);
  219.         }
  220.         if ($user) {
  221.             return $this->jwtService->createNewJWT($user);
  222.         }
  223.         return $this->json([
  224.             'success' => false,
  225.         ]);
  226.     }
  227. }