src\Controller\SecurityController.php line 219

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\User;
  4. use App\Form\ResetPasswordType;
  5. use App\Repository\UserRepository;
  6. use Doctrine\ORM\EntityManager;
  7. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  8. use Symfony\Component\HttpFoundation\JsonResponse;
  9. use Symfony\Component\HttpFoundation\Request;
  10. use Symfony\Component\HttpFoundation\Response;
  11. use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
  12. use Symfony\Component\Mailer\MailerInterface;
  13. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  14. use Symfony\Component\Routing\Annotation\Route;
  15. use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
  16. use Symfony\Bridge\Twig\Mime\TemplatedEmail;
  17. class SecurityController extends AbstractController
  18. {
  19.     /** @var UserPasswordHasherInterface */
  20.     private $passwordHasher;
  21.     public function __construct(UserPasswordHasherInterface $passwordHasher)
  22.     {
  23.         $this->passwordHasher $passwordHasher;
  24.     }
  25.     /**
  26.      * @Route("/login", name="auth-login")
  27.      */
  28.     public function login(AuthenticationUtils $authenticationUtils): Response
  29.     {
  30.         // get the login error if there is one
  31.         $error $authenticationUtils->getLastAuthenticationError();
  32.         // last username entered by the user
  33.         $lastUsername $authenticationUtils->getLastUsername();
  34.         /*
  35.         // Sample user record
  36.         $user = new User();
  37.         $user->setUsername('fkaynakli');
  38.         $user->setPassword(
  39.             $passEncoder->encodePassword($user, '123')
  40.         );
  41.         dump($user);
  42.         $em = $this->getDoctrine()->getManager();
  43.         $em->persist($user);
  44.         $em->flush();
  45.         */
  46.         return $this->render('security/login.html.twig', ['last_username' => $lastUsername'error' => $error]);
  47.     }
  48.     /**
  49.      * @Route("/logout", name="auth-logout")
  50.      */
  51.     public function logout(): void
  52.     {
  53.         throw new \LogicException('This method can be blank - it will be intercepted by the logout key on your firewall.');
  54.     }
  55.     /**
  56.      * @Route("/auth/hash-password", name="auth-hash-password")
  57.      */
  58.     public function hashPassword(Request $request): Response
  59.     {
  60.         if ($request->isMethod('POST')) {
  61.             if (empty($request->get('email'))) {
  62.                 $data json_decode($request->getContent(), true);
  63.                 $email $data['email'];
  64.                 $password $data['password'];
  65.                 $firma $data['firma'];
  66.             } else {
  67.                 $email $request->get('email');
  68.                 $password $request->get('password');
  69.                 $firma $request->get('firma');
  70.             }
  71.             if ($firma != $_ENV['FIRMA_KODU']) {
  72.                 return new Response('[success: false, msg:"Geçersiz firma : ' $firma '"]'Response::HTTP_NOT_FOUND);
  73.             }
  74.             /** @var UserRepository $rep */
  75.             $rep $this->getDoctrine()->getRepository(User::class);
  76.             $user $rep->findOneBy(['username' => $email]);
  77.             if ($user) {
  78.                 $passHash $this->passwordHasher->hashPassword($user$password);
  79.                 $user->setPassword($passHash);
  80.                 $em $this->getDoctrine()->getManager();
  81.                 $em->persist($user);
  82.                 $em->flush();
  83.                 return $this->json([
  84.                     'success' => true,
  85.                     'msg' => $email,
  86.                 ]);
  87.             } else return @new Response(json_encode([
  88.                 'success' => false,
  89.                 'msg' => "Kullanıcı blulunamadı!",
  90.                 'debug' => [$email$password$firma],
  91.             ]), Response::HTTP_NOT_FOUND);
  92.         }
  93.         return @new Response(json_encode([
  94.             'success' => false,
  95.             'msg' => "Eksik bilgi!",
  96.             'debug' => [$email$password$firma],
  97.         ]), Response::HTTP_NOT_FOUND);
  98.         //-return new Response($this->passwordHasher->hashPassword(new \App\Entity\User(), $request->get('password')));
  99.     }
  100.     /**
  101.      * @Route("/auth/eski-sifre", name="auth-eski-sifre")
  102.      */
  103.     public function eskiSifre(): Response
  104.     {
  105.         $user = new \App\Entity\User();
  106.         $connection $this->getDoctrine()->getConnection();
  107.         $connection->executeQuery("insert into MOBIL_KULLANICI (CARI_ID, KULLANICI_ADI, ALANLAR, MODULES)
  108.                 select C.CARI_ID, C.WEBUSERNAME, '[\"yemek\",\"dyemek\",\"kahvalti\",\"kumanya\",\"mesai\",\"folyo\",\"sefertasi\"," .
  109.             "\"ekmek\",\"dekmek\",\"ekstra1\",\"ekstra2\",\"ekstra3\",\"ekstra4\"]', 
  110.                     '[\"menu-index\",\"eirsaliye-index\",\"sayi-index\",\"efatura-index\",\"sarf-index\",\"demirbas-index\",\"crm-index\"," .
  111.             "\"siparis-index\", \"alerjen-index\", \"anket-index\", \"sozlesme-index\",\"ekmek-index\"]'
  112.                 from cari_kart C
  113.                 where C.WEBPASS is not null and not exists(
  114.                         select 1 from mobil_kullanici K where
  115.                             K.cari_id=C.cari_id
  116.                             and K.kullanici_adi = C.WEBUSERNAME)");
  117.         $kullanicilar $connection->executeQuery("select K.ID, C.WEBPASS from MOBIL_KULLANICI K
  118.                 inner join cari_kart C on C.cari_id = K.cari_id and C.WEBPASS IS NOT NULL
  119.                 where K.sifre IS NULL")
  120.             ->fetchAll();
  121.         try {
  122.             $i 0;
  123.             $c count($kullanicilar);
  124.             foreach ($kullanicilar as $kullanici) {
  125.                 printf('%d / %d şifre güncelleniyor...<br>', ++$i$c);
  126.                 $connection->executeQuery('update MOBIL_KULLANICI set SIFRE=:SIFRE where ID=:ID', [
  127.                     ':ID' => $kullanici['ID'],
  128.                     ':SIFRE' => $this->passwordHasher->hashPassword($user$kullanici['WEBPASS'])
  129.                 ]);
  130.                 if ($i >= 10 || $c 10) {
  131.                     echo '<script>location.reload();</script>';
  132.                     break;
  133.                 }
  134.             }
  135.         } catch (\Exception $e) {
  136.         } finally {
  137.             return new Response(sprintf('%d adet şifre güncellendi!'count($kullanicilar)));
  138.         }
  139.     }
  140.     /**
  141.      * @Route("auth/reset", name="auth-reset")
  142.      */
  143.     public function resetPassword(Request $requestMailerInterface $mailer): Response
  144.     {
  145.         $result = ['error' => null'email' => null'tag' => null];
  146.         $data = [
  147.             'email' => $request->get('email'null),
  148.             'tag' => $request->get('tag'null),
  149.             'password' => trim($request->get('password'null)),
  150.             'password2' => trim($request->get('password2'null)),
  151.         ];
  152.         if (filter_var($data['email'], FILTER_VALIDATE_EMAIL)) {
  153.             $result['email'] = $data['email'];
  154.             /** @var EntityManager $em */
  155.             $em $this->getdoctrine()->getmanager();
  156.             /** @var UserRepository $rep */
  157.             $rep $em->getrepository(User::class);
  158.             if ($request->isMethod('POST')) {
  159.                 $user $rep->findOneBy([
  160.                     'username' => $data['email'],
  161.                     'ActivationKey' => $data['tag'],
  162.                 ]);
  163.                 if (!$user) {
  164.                     $result['error'] = "Kullanıcı bulunamadı:\n" $data['email'] . "\n" $data['id'];
  165.                 } else {
  166.                     if (empty($data['password']) || ($data['password'] != $data['password2'])) {
  167.                         $result['error'] = 'Şifreler aynı değil!';
  168.                     } elseif (strlen($data['password']) < User::MIN_PASSWORD_LENGTH) {
  169.                         $result['error'] = sprintf('Şifre en az %d karakter uzunluğunda olmalı!'User::MIN_PASSWORD_LENGTH);
  170.                     } else {
  171.                         $user->setActivationKey(null);
  172.                         $user->setModifiedAt(null);
  173.                         $user->setPassword($rep->encodePassword($data['password']));
  174.                         try {
  175.                             $em->persist($user);
  176.                             $em->flush();
  177.                             $this->addFlash('success''Şifreniz başarıyla değiştirildi. Şimdi oturum açabilirsiniz.');
  178.                             return $this->redirectToRoute('auth-login');
  179.                         } catch (\Exception $e) {
  180.                             $result['error'] = sprintf("Şifre güncellenirken hata oluştu:\n%s"$e->getMessage());
  181.                         }
  182.                     }
  183.                 }
  184.             } else {
  185.                 $user $rep->findOneBy(['username' => $data['email']]);
  186.                 if (!$user) {
  187.                     $result['error'] = "Kullanıcı bulunamadı:\n" $data['email'] . "\n" $data['id'];
  188.                 } else {
  189.                     $result['tag'] = $user->getActivationKey();
  190.                     if ($result['tag'] != $data['tag']) {
  191.                         $result['error'] = 'Geçersiz şifre sıfırlama bağlantısı!';
  192.                     } elseif ($user->getModifiedAt()->getTimestamp() < time()) {
  193.                         $result['error'] = 'Zaman aşımından dolayı şifre sıfırlama yapamazsınız!';
  194.                     }
  195.                 }
  196.             }
  197.         } else {
  198.             $result['error'] = 'Geçersiz e-posta adresi: ' $data['email'];
  199.         }
  200.         return $this->render('security/reset.html.twig'$result);
  201.     }
  202.     /**
  203.      * @Route("auth/forgot", name="auth-forgot")
  204.      */
  205.     public function forgotPassword(Request $requestMailerInterface $mailer): Response
  206.     {
  207.         $result = ['email' => null'error' => null];
  208.         if ($request->isMethod('POST')) {
  209.             $result['email'] = $request->get('email');
  210.             $response $this->resetSendMail($request$mailer);
  211.             $response json_decode($response->getContent());
  212.             if (!$response->success) {
  213.                 $result['error'] = true;
  214.             }
  215.         }
  216.         return $this->render('security/forgot.html.twig'$result);
  217.     }
  218.     /**
  219.      * @Route("auth/reset/sendmail", name="auth-reset-sendmail")
  220.      */
  221.     public function resetSendMail(Request $requestMailerInterface $mailer): Response
  222.     {
  223.         if (empty($request->get('email'null))) {
  224.             $data json_decode($request->getContent(), true);
  225.         } else {
  226.             $data = [
  227.                 'email' => $request->get('email'null),
  228.                 'id' => $request->get('id'null),
  229.             ];
  230.         }
  231.         $result = ['success' => false'msg' => ''];
  232.         if (filter_var($data['email'], FILTER_VALIDATE_EMAIL)) {
  233.             $result['msg'] = $data['email'];
  234.             try {
  235.                 $filter = ['username' => $data['email']];
  236.                 if (!empty($data['id']))
  237.                     $filter['id'] = $data['id'];
  238.                 /** @var EntityManager $em */
  239.                 $em $this->getdoctrine()->getmanager();
  240.                 /** @var UserRepository $rep */
  241.                 $rep $em->getrepository(User::class);
  242.                 $user $rep->findOneBy($filter);
  243.                 if (!$user) {
  244.                     $result['msg'] = "Kullanıcı bulunamadı:\n" $data['email'] . "\n" $data['id'];
  245.                 } else {
  246.                     $data['tag'] = $user->generateActivationKey();
  247.                     $data['validuntil'] = $user->getModifiedAt()->getTimestamp();
  248.                     $em->persist($user);
  249.                     $em->flush();
  250.                     $this->sendEmail($data$mailer);
  251.                     $result['success'] = true;
  252.                 }
  253.             } catch (TransportExceptionInterface $e) {
  254.                 $result['msg'] = $e->getMessage();
  255.             } catch (\Exception $e) {
  256.                 $result['msg'] = $e->getMessage();
  257.             }
  258.         } else {
  259.             $result['msg'] = 'Geçersiz e-posta adresi: ' $data['email'];
  260.         }
  261.         return new JsonResponse($result);
  262.     }
  263.     /**
  264.      * Şifre sıfırlama formu için kullanıcıya eposta gönderir
  265.      * @param $data array
  266.      * @param MailerInterface $mailer
  267.      * @throws TransportExceptionInterface
  268.      */
  269.     protected function sendEmail(array $dataMailerInterface $mailer)
  270.     {
  271.         $email = (new TemplatedEmail())
  272.             ->to($data['email'])
  273.             ->subject('Foodsoft - Şifre Sıfırlama')
  274.             ->text('Şifre sıfırlama için aşağıdaki bağlantıyı kullanabilirsiniz!')
  275.             ->htmlTemplate('_email/reset-password.html.twig')
  276.             ->context(['kullanici' => $data]);
  277.         $mailer->send($email);
  278.     }
  279. }