src/Controller/AuthController.php line 174

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Model\DataObject\User;
  4. use App\Security\AppAuthenticator;
  5. use Carbon\Carbon;
  6. use Exception;
  7. use KnpU\OAuth2ClientBundle\Client\ClientRegistry;
  8. use Pimcore\Controller\FrontendController;
  9. use Pimcore\Log\Simple;
  10. use Pimcore\Mail;
  11. use Pimcore\Model\DataObject;
  12. use Pimcore\Model\DataObject\Folder;
  13. use Pimcore\Model\Element\Service;
  14. use Pimcore\Model\WebsiteSetting;
  15. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
  16. use Symfony\Component\HttpFoundation\Request;
  17. use App\Form\RecaptchaFormType;
  18. use Symfony\Component\Routing\Annotation\Route;
  19. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  20. use Symfony\Component\Security\Core\Security as FrontSecurity;
  21. use Symfony\Component\Security\Guard\GuardAuthenticatorHandler;
  22. use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
  23. use Symfony\Component\Validator\Constraints as Assert;
  24. use Symfony\Component\Validator\Validator\ValidatorInterface;
  25. class AuthController extends FrontendController
  26. {
  27.     /**
  28.      * @Template
  29.      * @param Request $request
  30.      * @param AuthenticationUtils $authenticationUtils
  31.      * @return array
  32.      * @Route(
  33.      *      "/{_locale}/login",
  34.      *      name="login"
  35.      * )
  36.      */
  37.     public function loginAction(Request $requestAuthenticationUtils $authenticationUtilsFrontSecurity $security)
  38.     {
  39.         $lang $request->getLocale();
  40.         $securityUser $security->getUser();
  41.         if ($securityUser) {
  42.             $user User::getByUsername($securityUser->getUserIdentifier())->load()[0];
  43.             return $this->redirect($this->getDefaultRoute($user));
  44.         }
  45.         // get the login error if there is one
  46.         $error $authenticationUtils->getLastAuthenticationError();
  47.         // last username entered by the user
  48.         $lastUsername $authenticationUtils->getLastUsername();
  49.         //dd($error);
  50.         return [
  51.             '_username' => $lastUsername,
  52.             'error' => $error,
  53.             '_target_path' => $request->get('_target_path') ?? null,
  54.         ];
  55.     }
  56.     /**
  57.      * @Route(
  58.      *      "/is-connected",
  59.      *      name="isConnected",
  60.      *      methods={"GET"}
  61.      * )
  62.      */
  63.     public function isConnected(FrontSecurity $security)
  64.     {
  65.         if ($security->getUser()) {
  66.             return $this->json(['res' => true]);
  67.         }
  68.         return $this->json(['res' => false]);
  69.     }
  70.     /**
  71.      * @Route("/{_locale}/login/after", name="afterLogin")
  72.      */
  73.     public function afterLogin(Request $requestFrontSecurity $security)
  74.     {
  75.         return $this->redirect('/' $request->getLocale());
  76.     }
  77.     /**
  78.      * Link to this controller to start the "connect" process
  79.      *
  80.      * @Route("/connect/{service}", name="connect_oauth")
  81.      */
  82.     public function connectWithOauth(Request $requestClientRegistry $clientRegistry)
  83.     {
  84.         $orderId $request->get("orderid");
  85.         if($orderId){
  86.             $order DataObject\Order::getById($orderId);
  87.             if($order){
  88.                 $url $clientRegistry
  89.                     ->getClient($request->get('service'))
  90.                     ->redirect(['email'], [])->getTargetUrl();
  91.                 $query_str parse_url($urlPHP_URL_QUERY);
  92.                 parse_str($query_str$query_params);
  93.                 if(isset($query_params["state"])){
  94.                     $order->setOauthState($query_params["state"]);
  95.                 }
  96.             }
  97.         }
  98.         return $clientRegistry
  99.             ->getClient($request->get('service'))
  100.             ->redirect(['email'], []);
  101.     }
  102.     /**
  103.      * @Template
  104.      *
  105.      * @Route("/oauth/check/{service}", name="oauth_check")
  106.      */
  107.     public function checkOauth(Request $requestFrontSecurity $security)
  108.     {
  109.         return [];
  110.     }
  111.     private function getDefaultRoute(User $user)
  112.     {
  113.         return '/' $user->getLang();
  114.     }
  115.     /**
  116.      * @Template
  117.      * @param Request $request
  118.      * @return \Symfony\Component\HttpFoundation\JsonResponse|\Symfony\Component\HttpFoundation\RedirectResponse
  119.      * @throws \Exception
  120.      * @Route(
  121.      *      "/{_locale}/reset/password/{renew_token}",
  122.      *      name="reset_password",
  123.      *      methods={"GET","POST"}
  124.      * )
  125.      */
  126.     public function resetPasswordAction(Request $request)
  127.     {
  128.         if ($request->isMethod('POST') && $request->get("new_password")) {
  129.             $user User::getById($request->get('user_id'));
  130.             if (!$user) {
  131.                 return ['error' => "Impossible de trouver l'utilisateur"];
  132.             }
  133.             $user->setPassword($request->get('new_password'));
  134.             $user->setRenewToken(null);
  135.             $user->setRenewExpire(null);
  136.             $user->save();
  137.             return $this->redirect($this->generateUrl("login"));
  138.         } elseif ($request->get("renew_token")) {
  139.             $user User::getByRenewToken($request->get("renew_token"))->load()[0];
  140.             if (!$user) {
  141.                 return $this->redirect($this->generateUrl('login'));
  142.             }
  143.             $expired false;
  144.             if ($user->getRenewExpire()->lt(Carbon::now())) {
  145.                 $expired true;
  146.             }
  147.             return ["user" => $user"expired" => $expired];
  148.         } else {
  149.             return $this->redirect($this->generateUrl('login'));
  150.         }
  151.     }
  152.     /**
  153.      * @Template
  154.      * @param Request $request
  155.      * @return \Symfony\Component\HttpFoundation\JsonResponse
  156.      * @throws \Exception
  157.      * @Route(
  158.      *      "/{_locale}/reset/password",
  159.      *      name="ask_reset_password",
  160.      *      methods={"GET","POST"}
  161.      * )
  162.      */
  163.     public function askResetPasswordAction(Request $requestFrontSecurity $security\Pimcore\Config\Config $websiteConfig)
  164.     {
  165.         $lang $request->getLocale();
  166.         if ($request->isMethod('POST') && $request->get('username')) {
  167.             $user User::getByUsername($request->get('username'))->load()[0];
  168.             if (!$user) {
  169.                 return ["error" => "Le compte n'existe pas"];
  170.             }
  171.             $token md5(time() * 10000);
  172.             $user->setRenewToken($token);
  173.             $nbrDays intval($websiteConfig->get('expirationDays')) === intval($websiteConfig->get('expirationDays'));
  174.             $user->setRenewExpire(Carbon::now()->addDay($nbrDays));
  175.             $user->save();
  176.             $mail = new Mail();
  177.             $mail->setDocument('/emails/' $lang "/reset-password");
  178.             $mail->to($user->getUsername());
  179.             $mail->setParam('renewLink'$this->generateUrl("reset_password", ['renew_token' => $token], UrlGeneratorInterface::ABSOLUTE_URL));
  180.             $mail->send();
  181.             return ["message" => "Vous avez reçu un lien pour modifier votre mot de passe par email."];
  182.         }
  183.     }
  184.     /**
  185.      * @Template
  186.      * @Route(
  187.      *      "/{_locale}/register",
  188.      *      name="register",
  189.      *      methods={"GET","POST"}
  190.      * )
  191.      */
  192.     public function registerAction(Request $requestFrontSecurity $security\Pimcore\Config\Config $websiteConfigValidatorInterface $validator)
  193.     {
  194.         $formStatus false;
  195.         $honeypotValue "Waterloo";
  196.         // initialize form and handle request data
  197.         $formContact $this->createForm(RecaptchaFormType::class, null);
  198.         $formContact->handleRequest($request);
  199.         Simple::log('apk_register''Start new user');
  200.         $securityUser $security->getUser();
  201.         if ($securityUser) {
  202.             $user User::getByUsername($securityUser->getUserIdentifier())->load()[0];
  203.             return $this->redirect($this->getDefaultRoute($user));
  204.         }
  205.         /** @var Pimcore\Model\DataObject */
  206.         $countries DataObject\Service::getOptionsForSelectField("Pimcore\Model\DataObject\User""country");
  207.         if ($request->isMethod('POST')) {
  208.             $orderid $request->get("orderid");
  209.             foreach (['email''password''confirm-password'] as $required_field) {
  210.                 $isSet false;
  211.                 if (is_array($required_field)) {
  212.                     foreach ($required_field as $field) {
  213.                         if ($request->get($field)) {
  214.                             $isSet true;
  215.                         }
  216.                     }
  217.                 } else {
  218.                     $isSet $request->get($required_field);
  219.                 }
  220.                 if (!$isSet) {
  221.                     return ["error" => "Vous devez remplir tous les champs.","countries" => $countries"previousValues" => $request->request->all(), 'form' => $formContact->createView(), "formStatus" => $formStatus"honeypotValue" => $honeypotValue];
  222.                 }
  223.             }
  224.             $email $request->get('email');
  225.             $password $request->get('password');
  226.             $confirmPassword $request->get('confirm-password');
  227.             if ($password !== $confirmPassword) {
  228.                 return ["error" => "Les 2 mots de passe ne sont pas identiques","countries" => $countries"previousValues" => $request->request->all(), 'form' => $formContact->createView(), "formStatus" => $formStatus"honeypotValue" => $honeypotValue];
  229.             }
  230.             /** @var Symfony\Component\Validator\Constraints as Assert  */
  231.             $emailConstraint = new Assert\Email();
  232.             $errors $validator->validate($email$emailConstraint);
  233.             if (count($errors) > 0) {
  234.                 return ["error" => $errors[0]->getMessage(),"countries" => $countries"previousValues" => $request->request->all(), 'form' => $formContact->createView(), "formStatus" => $formStatus"honeypotValue" => $honeypotValue];
  235.             }
  236.             $checkUser User::getByUsername($email, ['limit' => 1'unpublished' => true]);
  237.             if ($checkUser) {
  238.                 $now Carbon::now();
  239.                 if($checkUser->getPublished()){
  240.                     return ["message" => 'Le compte existe déjà, <a href="' $this->generateUrl('login') . '">connectez-vous</a> ou <a href="' $this->generateUrl('ask_reset_password') . '">cliquez ici</a> pour réinitialiser votre mot de passe',"countries" => $countries"previousValues" => $request->request->all(), 'form' => $formContact->createView(), "formStatus" => $formStatus"honeypotValue" => $honeypotValue];
  241.                 }else{
  242.                     if($checkUser->getStatus() == "unverified"){
  243.                         if(($now->timestamp $checkUser->getCreationDate()) > 60){
  244.                             $token md5(uniqid('renew_token'true));
  245.                             $checkUser->setRenewToken($token);
  246.                             $nbrDays intval($websiteConfig->get('expirationDays')) === intval($websiteConfig->get('expirationDays'));
  247.                             $checkUser->setRenewExpire(Carbon::now()->addDays($nbrDays));
  248.                             $checkUser->save();
  249.                             if($orderid){
  250.                                 $order DataObject\Order::getById($orderid);
  251.                                 if($order && !$order->getLinkedUser()){
  252.                                     $order->setLinkedUser($checkUser);
  253.                                     $order->save();
  254.                                 }
  255.                             }
  256.                             /*$mail = new Mail();
  257.                             $mail->setDocument('/emails/' . $request->getLocale() . "/verify-email");
  258.                             $mail->to($checkUser->getUsername());
  259.                             $mail->setParam('Link', $this->generateUrl('verify_email_itsme', ['renew_token' => $checkUser->getRenewToken()], UrlGeneratorInterface::ABSOLUTE_URL));
  260.                             $mail->send();*/
  261.                         }else{
  262.                             Simple::log('apk_register''less that 60seconds since first register mail');
  263.                         }
  264.                         return $this->redirectToRoute('verify_email_itsme', ['renew_token' => $checkUser->getRenewToken()]);
  265.                         //return ["message" => "Votre adresse email doit être confirmée, vous allez recevoir un email de confirmation", "message_title" => "You've got mail!"];
  266.                     }else{
  267.                         return ["message" => 'Il semblerait que votre compte soit désactivé. Veuillez nous contacter.',"countries" => $countries"previousValues" => ["gender" => """firstname" => """lastname" => """email" => """password" => """confirm-email" => """phone" => ""'street' => '''zip' => '''country' => '''city' => '''prefix' => '+32'], 'form' => $formContact->createView(), "formStatus" => $formStatus"honeypotValue" => $honeypotValue];
  268.                     }
  269.                 }
  270.             }
  271.             $data $formContact->getData();
  272.             // fake variable
  273.             $address $_POST["address"];
  274.             // reCaptcha verification
  275.             $recaptchaKeyPrivate WebsiteSetting::getByName('recaptchaKeyPrivate');
  276.             $recaptcha_url 'https://www.google.com/recaptcha/api/siteverify';
  277.             $recaptcha_response $data['recaptcha'];
  278.             $recaptcha file_get_contents($recaptcha_url '?secret=' $recaptchaKeyPrivate->getData() . '&response=' $recaptcha_response);
  279.             $recaptcha json_decode($recaptcha);
  280.             if ($recaptcha->success && isset($recaptcha->score) && $recaptcha->score >= 0.3 && $address == $honeypotValue)
  281.             {
  282.                 $user = new User();
  283.                 $user->setUsername($email);
  284.                 $user->setEmail($email);
  285.                 $user->setLang($request->getLocale());
  286.                 $user->setRecaptchaScore($recaptcha->score);
  287.                 $user->setPassword($password);
  288.                 $user->setRoles(["ROLE_USER"]);
  289.                 $user->setStatus("unverified");
  290.                 $keyname Service::getValidKey($email'object');
  291.                 $user->setKey($keyname);
  292.                 $user->setParent(Folder::getByPath('/users') ?? Folder::create(['o_parentId' => 1'o_key' => 'users']));
  293.                 $user->setPublished(false);
  294.                 $token md5(uniqid('renew_token'true));
  295.                 $user->setRenewToken($token);
  296.                 $nbrDays intval($websiteConfig->get('expirationDays')) === intval($websiteConfig->get('expirationDays'));
  297.                 $user->setRenewExpire(Carbon::now()->addDays($nbrDays));
  298.                 if (WebsiteSetting::getByName("parrainage")) {
  299.                     if ($request->get('parrain')) {
  300.                         $parrain User::getByParrainageToken($request->get('parrain'))->load();
  301.                         if ($parrain) {
  302.                             $parrain $parrain[0];
  303.                         } else {
  304.                             return ["error" => "Ce code de parrainage n'existe pas.""countries" => $countries"previousValues" => ["gender" => """firstname" => """lastname" => """email" => $email"password" => $password"confirm-email" => """phone" => ""'street' => '''zip' => '''country' => '''city' => '''prefix' => '+32'], 'form' => $formContact->createView(), "formStatus" => $formStatus"honeypotValue" => $honeypotValue];
  305.                         }
  306.                         $user->setParrain($parrain);
  307.                     }
  308.                 }
  309.                 $user->save();
  310.                 if($orderid){
  311.                     $order DataObject\Order::getById($orderid);
  312.                     if($order && !$order->getLinkedUser()){
  313.                         $order->setLinkedUser($user);
  314.                         $order->save();
  315.                     }
  316.                 }
  317.                 /*$mail = new Mail();
  318.                 $mail->setDocument('/emails/' . $request->getLocale() . "/verify-email");
  319.                 $mail->to($user->getUsername());
  320.                 $mail->setParam('Link', $this->generateUrl('verify_email_itsme', ['renew_token' => $user->getRenewToken()], UrlGeneratorInterface::ABSOLUTE_URL));
  321.                 $mail->send();*/
  322.                 return $this->redirectToRoute('verify_email_itsme', ['renew_token' => $user->getRenewToken()]);
  323.                 //return ["message" => "Votre adresse email doit être confirmée, vous allez recevoir un email de confirmation", "message_title" => "You've got mail!", 'form' => $formContact->createView(), "formStatus" => $formStatus];
  324.             }else{
  325.                 $formStatus 'robot';
  326.             }
  327.         }
  328.         return ["countries" => $countries"previousValues" => ["gender" => """firstname" => """lastname" => """email" => """password" => """confirm-email" => """phone" => ""'street' => '''zip' => '''country' => '''city' => '''prefix' => '+32'], 'form' => $formContact->createView(), "formStatus" => $formStatus"honeypotValue" => $honeypotValue];
  329.     }
  330.     /**
  331.      * @Template
  332.      * @Route(
  333.      *      "{_locale}/verify-email/itsme/{renew_token}",
  334.      *      name="verify_email_itsme",
  335.      *      methods={"GET"}
  336.      * )
  337.      */
  338.     public function verifyEmailItsmeAction(Request $request\Pimcore\Config\Config $websiteConfig,
  339.                                            GuardAuthenticatorHandler $guard,
  340.                                            AppAuthenticator $formAuthenticator)
  341.     {
  342.         if ($request->get('renew_token')) {
  343.             $user User::getByRenewToken($request->get("renew_token"), ['limit' => 1'unpublished' => true]);
  344.             if (!$user) {
  345.                 return ["error" => "Vous devez définir un token valide""message" => false];
  346.             }
  347.             $user->setPublished(true);
  348.             $user->save();
  349.             //login automatique du user
  350.             $guard->authenticateUserAndHandleSuccess(
  351.                 $user,
  352.                 $request,
  353.                 $formAuthenticator,
  354.                 'app_admin'
  355.             );
  356.             return ["userid" => $user->getId()];
  357.         } else {
  358.             return ["error" => "Vous devez définir un token valide""message" => false];
  359.         }
  360.     }
  361.     /**
  362.      * @Template
  363.      * @Route(
  364.      *      "{_locale}/verify-email/{renew_token}",
  365.      *      name="verify_email",
  366.      *      methods={"GET"}
  367.      * )
  368.      */
  369.     public function verifyEmailAction(Request $request\Pimcore\Config\Config $websiteConfig)
  370.     {
  371.         if ($request->get('renew_token')) {
  372.             $user User::getByRenewToken($request->get("renew_token"), ['limit' => 1'unpublished' => true]);
  373.             if (!$user) {
  374.                 return ["error" => "Vous devez définir un token valide""message" => false];
  375.             }
  376.             $user->setRenewToken(null);
  377.             $user->setRenewExpire(null);
  378.             $user->setStatus("verified");
  379.             $user->save();
  380.             $countries DataObject\Service::getOptionsForSelectField("Pimcore\Model\DataObject\User""country");
  381.             return $this->render('user/details.html.twig',
  382.                 ["user" => $user"countries" => $countries"message" => "You have been verified."]
  383.             );
  384.         } else {
  385.             return ["error" => "Vous devez définir un token valide""message" => false];
  386.         }
  387.     }
  388.     /**
  389.      * @Route("/before-logout", name="beforeLogout", methods={"GET"})
  390.      */
  391.     public function beforeLogout()
  392.     {
  393.         // \Pimcore\Cache::clearTag("pimcore_viewcache_header_cache");
  394.         return $this->redirectToRoute("logout");
  395.     }
  396.     /**
  397.      * @Route("/logout", name="logout", methods={"GET"})
  398.      */
  399.     public function logout()
  400.     {
  401.         // controller can be blank: it will never be executed!
  402.         throw new \Exception('Don\'t forget to activate logout in security.yaml');
  403.     }
  404. }