<?php
/**
* @version EC=CUBE4
* @copyright 株式会社 翔 kakeru.co.jp
* @author
* 2021年12月17日作成
*
* app\Customize\Controller\ForgotController.php
*
*
* ForgotController.phpのカスタマイズ
*
*
*
* C= C= C= ┌(;・_・)┘トコトコ
******************************************************/
namespace Customize\Controller;
use Customize\Service\Google\ReCaptchaService;
use Eccube\Event\EccubeEvents;
use Eccube\Event\EventArgs;
use Eccube\Form\Type\Front\ForgotType;
# use Eccube\Form\Type\Front\PasswordResetType;
use Eccube\Repository\CustomerRepository;
use Eccube\Service\MailService;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception as HttpException;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Security\Core\Encoder\EncoderFactoryInterface;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\Validator\ValidatorInterface;
use Customize\Form\Type\Front\PasswordResetType;
use Eccube\Entity\Master\job;
use Customize\Service\CartService;
use Customize\Service\CustomerService;
use Customize\Converter\CustomerConverter;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
class ForgotController extends \Eccube\Controller\ForgotController{
protected $CustomerService;
protected $CustomerConverter;
protected $tokenStorage;
protected $session;
protected $cartService;
protected $reCaptchaService;
public function __construct(
ValidatorInterface $validator,
MailService $mailService,
CustomerRepository $customerRepository,
EncoderFactoryInterface $encoderFactory,
CustomerService $CustomerService,
CustomerConverter $CustomerConverter,
TokenStorageInterface $tokenStorage,
SessionInterface $session,
CartService $cartService,
ReCaptchaService $reCaptchaService
) {
$this->validator = $validator;
$this->mailService = $mailService;
$this->customerRepository = $customerRepository;
$this->encoderFactory = $encoderFactory;
$this->CustomerService = $CustomerService;
$this->CustomerConverter = $CustomerConverter;
$this->tokenStorage = $tokenStorage;
$this->session = $session;
$this->cartService = $cartService;
$this->reCaptchaService = $reCaptchaService;
}
/**
* パスワードリマインダ.
*
* @Route("/forgot/", name="forgot", methods={"GET", "POST"})
* @Template("Forgot/index.twig")
*/
public function index(Request $request)
{
if ($this->isGranted('ROLE_USER')) {
throw new HttpException\NotFoundHttpException();
}
if ($request->getMethod() === 'GET') {
$referer = $request->headers->get('referer');
$this->session->set('referer', $referer);
}
$builder = $this->formFactory
->createNamedBuilder('', ForgotType::class);
$event = new EventArgs(
[
'builder' => $builder,
],
$request
);
$this->eventDispatcher->dispatch($event, EccubeEvents::FRONT_FORGOT_INDEX_INITIALIZE);
$form = $builder->getForm();
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$this->reCaptchaService->handleRequest($request);
$Customer = $this->customerRepository
->getRegularCustomerByEmail($form->get('login_email')->getData());
if (is_null($Customer)) {
if ($LmCustomer = $this->CustomerService->GetLandMarkCustomerEmail($form->get('login_email')->getData())){
list($Customer,$RetKey) = $this->CustomerService->SetCustomer($Customer,$LmCustomer,false);
}
}
if (!is_null($Customer)) {
// リセットキーの発行・有効期限の設定
$Customer
->setResetKey($this->customerRepository->getUniqueResetKey())
->setResetExpire(new \DateTime('+'.$this->eccubeConfig['eccube_customer_reset_expire'].' min'));
// リセットキーを更新
$this->entityManager->persist($Customer);
$this->entityManager->flush();
$event = new EventArgs(
[
'form' => $form,
'Customer' => $Customer,
],
$request
);
$this->eventDispatcher->dispatch($event, EccubeEvents::FRONT_FORGOT_INDEX_COMPLETE);
// 完了URLの生成
$reset_url = $this->generateUrl('forgot_reset', ['reset_key' => $Customer->getResetKey()], UrlGeneratorInterface::ABSOLUTE_URL);
// メール送信
$this->mailService->sendPasswordResetNotificationMail($Customer, $reset_url);
// ログ出力
log_info('send reset password mail to:'."{$Customer->getId()} {$Customer->getEmail()} {$request->getClientIp()}");
} else {
log_warning(
'Un active customer try send reset password email: ',
['Enter email' => $form->get('login_email')->getData()]
);
}
return $this->redirectToRoute('forgot_complete');
}
return [
'form' => $form->createView(),
'BreadCrumbs' => [],
'reCaptchaSiteKey' => $this->reCaptchaService->getReCaptchaSiteKey()
];
}
/**
* 再設定URL送信完了画面.
*
* @Route("/forgot/complete/", name="forgot_complete", methods={"GET"})
* @Template("Forgot/complete.twig")
*/
public function complete(Request $request)
{
if ($this->isGranted('ROLE_USER')) {
throw new HttpException\NotFoundHttpException();
}
return [
'BreadCrumbs' => [],
];
}
/**
* パスワード再発行実行画面.
*
* @Route("/forgot/reset/{reset_key}/", name="forgot_reset", methods={"GET", "POST"})
* @Template("Forgot/reset.twig")
*/
public function reset(Request $request, $reset_key)
{
if ($this->isGranted('ROLE_USER')) {
throw new HttpException\NotFoundHttpException();
}
$carts = $this->cartService->getCarts();
$referer = $this->session->get('referer', null);
if ($request->getMethod() === 'GET' && is_null($referer)) {
$referer = $request->headers->get('referer');
$this->session->set('referer', $referer);
}
$errors = $this->validator->validate(
$reset_key,
[
new Assert\NotBlank(),
new Assert\Regex(
[
'pattern' => '/^[a-zA-Z0-9]+$/',
]
),
]
);
if (count($errors) > 0) {
// リセットキーに異常がある場合
throw new HttpException\NotFoundHttpException();
}
$Customer = $this->customerRepository
->getRegularCustomerByResetKey($reset_key);
if (null === $Customer) {
// リセットキーから会員データが取得できない場合
throw new HttpException\NotFoundHttpException();
}
$builder = $this->formFactory
->createNamedBuilder('', PasswordResetType::class);
$form = $builder->getForm();
#2021/12/20 kakeru
$this->CustomerService->SetFirstLoginFlg(0);
if (!$Customer->getPassword()){
$this->CustomerService->SetFirstLoginFlg(1);
if($Email=$this->session->get(CustomerService::LM_Customer_Email )){
$this->CustomerService->SetFirstLoginFlg(2);
$form->get('login_email')->setData($Email);
$this->session->set(CustomerService::LM_Customer_Email,null);
}
}
$form->handleRequest($request);
$error = null;
if ($form->isSubmitted() && $form->isValid()) {
// リセットキー・入力メールアドレスで会員情報検索
$Customer = $this->customerRepository
->getRegularCustomerByResetKey($reset_key, $form->get('login_email')->getData());
if ($Customer) {
// パスワードの発行・更新
$encoder = $this->encoderFactory->getEncoder($Customer);
$pass = $form->get('password')->getData();
$Customer->setPassword($pass);
// 発行したパスワードの暗号化
if ($Customer->getSalt() === null) {
$Customer->setSalt($this->encoderFactory->getEncoder($Customer)->createSalt());
}
$encPass = $encoder->encodePassword($pass, $Customer->getSalt());
// パスワードを更新
$Customer->setPassword($encPass);
// リセットキーをクリア
$Customer->setResetKey(null);
#2021/12/20 kakeru 業種の登録
if ($Job=$form->get('job')->getData()){
$Customer->setJob($Job);
}
// パスワードを更新
$this->entityManager->persist($Customer);
$this->entityManager->flush();
#2021/12/22 kakeru LMDATAの送信
$this->CustomerConverter->SetCustomer($Customer);
$event = new EventArgs(
[
'Customer' => $Customer,
],
$request
);
$this->eventDispatcher->dispatch($event, EccubeEvents::FRONT_FORGOT_RESET_COMPLETE);
// 完了メッセージを設定
$this->addFlash('password_reset_complete', trans('front.forgot.reset_complete'));
$token = new UsernamePasswordToken($Customer, null, 'customer', ['ROLE_USER']);
$this->tokenStorage->setToken($token);
$request->getSession()->migrate(true);
if (is_object($carts) || is_array($carts)) {
foreach ($carts as $cart) {
$persistedCarts = $this->cartService->getPersistedCarts();
// if cart type is catalog, remove old persisted cart of user
if ($cart->getCartType() === CartService::CartTypeCatalog && $token->getUser() && (is_object($persistedCarts) || is_array($persistedCarts))) {
$this->removePersistedCart($persistedCarts);
}
$cartKeys = $this->session->get('cart_keys', []);
$isCatalogCart = false;
if ((count($persistedCarts) > 0) && !in_array($persistedCarts[0]->getCartKey(), $cartKeys, true)) {
foreach ($persistedCarts as $cartPersisted) {
if ($cartPersisted->getCartType() === CartService::CartTypeCatalog) {
$isCatalogCart = true;
break;
}
}
if ($isCatalogCart) {
$this->removePersistedCart($persistedCarts);
}
}
$cart->setCustomer($this->getUser());
$this->entityManager->persist($cart);
$this->entityManager->flush();
}
}
$referer = $this->session->get('referer');
$domain = $this->eccubeConfig['UT_URL'];
if ($referer && strpos($referer, $domain) !== false) {
return $this->redirect($referer);
} elseif ($referer == "shopping" || is_object($carts) || is_array($carts)) {
return $this->redirectToRoute('shopping');
}
// ログインページへリダイレクト
return $this->redirectToRoute('mypage_login');
} else {
// リセットキー・メールアドレスから会員データが取得できない場合
$error = trans('front.forgot.reset_not_found');
}
}
return [
'error' => $error,
'form' => $form->createView(),
'Flg' =>$this->CustomerService->GetFirstLoginFlg(),
];
}
private function removePersistedCart($persistedCarts)
{
foreach ($persistedCarts as $persistedCart){
$this->entityManager->remove($persistedCart);
$this->entityManager->flush();
}
}
}