src/Controller/Security/SecurityController.php line 41

Open in your IDE?
  1. <?php
  2. namespace App\Controller\Security;
  3. use App\Repository\TManagerRepository;
  4. use App\Utils\Globals;
  5. use App\Utils\ResponseMessage;
  6. use App\Entity\TManager;
  7. use App\Service\DefaultService;
  8. use Exception;
  9. use Swift_Mailer;
  10. use Swift_Message;
  11. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  12. use Symfony\Component\HttpFoundation\JsonResponse;
  13. use Symfony\Component\HttpFoundation\RedirectResponse;
  14. use Symfony\Component\Routing\Annotation\Route;
  15. use Symfony\Component\HttpFoundation\Response;
  16. use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
  17. use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
  18. use Symfony\Component\Security\Csrf\TokenStorage\TokenStorageInterface;
  19. use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
  20. use Transliterator;
  21. class SecurityController extends  AbstractController {
  22.     private Globals $globals;
  23.     private TManagerRepository $managerRepo;
  24.     public function __construct(Globals $globalsTManagerRepository $managerRepo)
  25.     {
  26.         $this->globals $globals;
  27.         $this->managerRepo $managerRepo;
  28.     }
  29.     /**
  30.      * @Route("/login", name="security_login")
  31.      * @param AuthenticationUtils $helper
  32.      * @return Response
  33.      */
  34.     public function login(AuthenticationUtils $helper){
  35.         return $this->render('security/login.html.twig', [
  36.             'last_username' => $helper->getLastUsername(),
  37.             'error' => $helper->getLastAuthenticationError(),
  38.         ]);
  39.     }
  40.     /**
  41.      * @Route("/checklogin", name="security_check_login")
  42.      * @param UserPasswordEncoderInterface $passwordEncoder
  43.      * @return JsonResponse
  44.      */
  45.     public function checklogin(UserPasswordEncoderInterface $passwordEncoder): JsonResponse
  46.     {
  47.         $data json_decode(file_get_contents('php://input'), false);
  48.         if (!isset($data->username$data->password))
  49.             return new JsonResponse(ResponseMessage::MSG_FORM_INVALID200);
  50.         $username $data->username;
  51.         $password $data->password;
  52.         $login $this->managerRepo->findOneBy(['username' => $username'active' =>  true]);
  53.         if (!$login)
  54.             $login $this->managerRepo->findBy(array('email' => $username'active' =>  true));
  55.         if (!$login)
  56.             return new JsonResponse(ResponseMessage::MSG_LOGIN_NOT_FOUND200);
  57.         if (!$passwordEncoder->isPasswordValid($login$password))
  58.             return new JsonResponse(ResponseMessage::MSG_PASSWORD_NOTMATCH200);
  59.         $this->authenticateUser($login);
  60.         return new JsonResponse(array('status' => 1'message' => ResponseMessage::MSG_SUCCESS'url' => $this->generateUrl('dashbord')), 200);
  61.     }
  62.     /**
  63.      * @Route("/logout", name="security_logout")
  64.      * @throws Exception
  65.      */
  66.     public function logout(): void {
  67.         throw new Exception('This should never be reached!');
  68.     }
  69.     /**
  70.      * @Route("/invitation/", name="invitation")
  71.      */
  72.     public function resetPassword(): Response {
  73.         return $this->render('security/password/invitation.html.twig');
  74.     }
  75.     /**
  76.      * @Route("/getinvitation/", name="getInvitation")
  77.      * @param Swift_Mailer $mailer
  78.      * @param TokenStorageInterface $tokenStorage
  79.      * @return JsonResponse
  80.      */
  81.     public function getInvitation(Swift_Mailer $mailer): JsonResponse{
  82.         $postdata file_get_contents('php://input');
  83.         $request json_decode($postdata);
  84.         if (!isset($request->email)) return new JsonResponse(ResponseMessage::MSG_FORM_INVALID200);
  85.         $user $request->email;
  86.         $user $this->managerRepo->findOneBy(['username' => $user]);
  87.         if (!$user) return new JsonResponse('email not found'200);
  88.         if ($user->getPasswordState() !== 'tochange' || empty($user->getPasswordToken())){
  89.             $user->setPasswordToken(uniqid(mt_rand(), true));
  90.             $user->setPasswordState('tochange');
  91.             $this->globals->em()->persist($user);
  92.             $this->globals->em()->flush();
  93.         }
  94.         $message = (new Swift_Message('OPAIE - Invitation'))
  95.             ->setFrom(DefaultService::$EMAIL_FROM)
  96.             ->setTo($user->getUsername())
  97.             ->setBody(
  98.                 $this->renderView(
  99.                     'email/opaie/passwordToken.html.twig', array('fullname' => $user->getPsoeudo(), 'token' => $user->getPasswordToken())
  100.                 ),
  101.                 'text/html'
  102.             );
  103.         $sent $mailer->send($message);
  104.         if ($sent === 0)
  105.             return new JsonResponse(ResponseMessage::MSG_MAIL_NOT_SENT200);
  106.         return new JsonResponse(array('status' => ResponseMessage::MSG_SUCCESS'data' => $sent), 200);
  107.     }
  108.     /**
  109.      * @Route("/validChangePassword/", name="validChangePassword")
  110.      * @param UserPasswordEncoderInterface $passwordEncoder
  111.      * @param TokenStorageInterface $tokenStorage
  112.      * @return JsonResponse
  113.      */
  114.     public function validChangePassword(UserPasswordEncoderInterface $passwordEncoder): JsonResponse {
  115.         $postdata file_get_contents('php://input');
  116.         $request json_decode($postdata);
  117.         if (!isset($request->password1$request->password2$request->token)){
  118.             return new JsonResponse(ResponseMessage::MSG_FORM_INVALID200);
  119.         }
  120.         $password1 $request->password1$password2 $request->password2$token $request->token;
  121.         if ($password1 !== $password2) { return new JsonResponse('password not match'); }
  122.         if (strlen($password1) < 4) { return new JsonResponse('password too short'); }
  123.         $user $this->managerRepo->findBy(['password_token' => $token'password_state' => 'tochange']);
  124.         if (!$user) { return new JsonResponse('token invalid'200); }
  125.         $user $user[0];
  126.         $user->setPassword($passwordEncoder->encodePassword($user$password1));
  127.         $user->setPasswordState('changed');
  128.         $user->setPasswordToken(null);
  129.         $this->globals->em()->persist($user);
  130.         $this->globals->em()->flush();
  131.         return new JsonResponse(array('status' => ResponseMessage::MSG_SUCCESS'data' => null), 200);
  132.     }
  133.     /**
  134.      * @Route("/resetPasword/{token}/", name="security_reset_password")
  135.      * @param $token
  136.      * @param TokenStorageInterface $tokenStorage
  137.      * @return RedirectResponse|Response
  138.      */
  139.     public function resetPasword($token) {
  140.         if (!$token) return $this->redirectToRoute('dashbord');
  141.         $user $this->managerRepo->findBy(['password_token' => $token]);
  142.         if (!$user) return $this->redirectToRoute('dashbord');
  143.         $user $user[0];
  144.         return $this->render('security/password/resetPassword.html.twig', array('user' => $user));
  145.     }
  146.     private function authenticateUser(TManager $user){
  147.         $providerKey 'database_users'// your firewall name
  148.         $token = new UsernamePasswordToken($usernull$providerKey$user->getRoles());
  149.         $this->get('security.token_storage')->setToken($token);
  150.         $this->get('session')->set('_security_main'serialize($token));
  151.     }
  152.     /**
  153.      * @param $string
  154.      * @return string|string[]|null
  155.      */
  156.     public function slugify($string) {
  157.         $rule 'NFD; [:Nonspacing Mark:] Remove; NFC';
  158.         $transliterator Transliterator::create($rule);
  159.         $string $transliterator->transliterate($string);
  160.         return preg_replace(
  161.             '/[^a-z0-9]/',
  162.             '',
  163.             strtolower(trim(strip_tags($string)))
  164.         );
  165.     }
  166. }