<?php
namespace App\Controller;
use App\Entity\Usertable;
use App\Entity\Companytable;
use App\Entity\Logtable;
use App\DTO\UserMailDTO;
use App\DTO\UserPasswordDTO;
use App\Form\UserMailForm;
use App\Form\UserPasswordForm;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
use Symfony\Component\Form\Extension\Core\Type\RepeatedType;
use Symfony\Component\Form\FormBuilderInterface;
class SecurityController extends AbstractController
{
private $mailer;
public function __construct(\Swift_Mailer $mailer)
{
$this->mailer = $mailer;
\Swift_DependencyContainer::getInstance()
->register('mime.qpheaderencoder')
->asAliasOf('mime.base64headerencoder');
\Swift_Preferences::getInstance()->setCharset('iso-2022-jp');
}
/**
* @Route("/login", name="app_login")
*/
public function login(AuthenticationUtils $authenticationUtils): Response
{
if ($this->getUser() ) {
if ($this->getUser()->getDeleted() ) {
return $this->redirectToRoute('default');
}
// return $this->redirectToRoute('user_del_logout');
}
// get the login error if there is one
$error = $authenticationUtils->getLastAuthenticationError();
// last username entered by the user
$lastUsername = $authenticationUtils->getLastUsername();
return $this->render('security/login.html.twig', ['last_username' => $lastUsername, 'error' => $error]);
}
// このtiwgは存在しなくなった為一旦非表示
// /**
// * @Route("/userDelete", name="user_del_logout")
// */
// public function userDel()
// {
// return $this->render('security/userDelLogout.html.twig', []);
// }
/**
* @Route("/logout", name="app_logout")
*/
public function logout()
{
throw new \LogicException('This method can be blank - it will be intercepted by the logout key on your firewall.');
}
/**
* @Route("/login/password", name="login_password")
*/
public function password(Request $request): Response
{
if ($this->getUser()) {
return $this->redirectToRoute('default');
}
$error = "";
$user = new Usertable();
$user_dto = new UserMailDTO($user);
$form = $this->createForm(UserMailForm::class, $user_dto);
$form->handleRequest($request);
if ($form->isSubmitted()){
$em = $this->getDoctrine()->getManager();
$mail = $request->request->get('user_mail_form');
$t = explode(" ",microtime());
$minisecond = substr((string)$t[0],2,0);
$date = date("Y-m-d H:i:s". $minisecond);
$repoUser = $em->getRepository(Usertable::class);
$user = $repoUser->findOneBy(['deleted' => 0, 'mailaddress' => $mail['mailaddress']]);
if(empty($user)){
$error = "メールアドレスが登録されていません。";
}else{
try {
$em->beginTransaction();
$user->setUpdated(new \DateTime($date));
$user->setUpdatedby('password');
//メールを送信する処理を追加する
$user->setHash(md5($user->getMailaddress().$date));
$user->setValidityperiod(new \DateTime(date("Y-m-d H:i:s", $minisecond.strtotime("+30 min"))));
$em->persist($user);
$em->flush();
$this->sendMail($user);
// Log記入
$array = [];
$array["mailAddress"] = $mail['mailaddress'];
$array["userid"] = $user->getId();
$array["updated"] = $user->getUpdated()->format("Y/m/d H:i:s");
$array["updatedby"] = $user->getUpdatedby();
$array["loginId"] = $user->getLoginid();
$array["hash"] = $user->getHash();
$array["validityPeriod"] = $user->getValidityPeriod()->format("Y/m/d H:i:s");
$em->getRepository(Logtable::class)->addLogs($em, $user, (new \DateTime($date)), 3, $array);
$em->getConnection()->commit();
}
catch(Exception $ex)
{
$em->getConnection()->rollback();
$this->addFlash('error', '予期せぬエラーが発生しました。\nお手数ではございますが、システム管理者に連絡をお願い致します。');
}
return $this->render('security/mail.html.twig', [
]);
}
}
return $this->render('security/password.html.twig', [
'error' => $error,
'form' => $form->createView(),
]);
}
public function sendMail($Usertable)
{
$em = $this->getDoctrine()->getManager();
$fromaddr = ['ssc-info@stellarlink.co.jp' => 'ステラサインクラウド事務局'];
$url = $this->generateUrl(
'set_password',
array('hash' => $Usertable->getHash()),
UrlGeneratorInterface::ABSOLUTE_URL
);
$content = "$url";
$repoCompany = $em->getRepository(Companytable::class);
$company = $repoCompany->findOneBy(['deleted' => '0','id' => $Usertable->getCompanyid()]);
$companyName = $company->getCompanyname();
$name = $Usertable->getName();
$toaddr = $Usertable->getMailaddress();
$mailbody = str_replace("<br>","\r\n", $content);
$mailtitle = "【ステラサインクラウド】パスワード変更受付のご連絡";
$message = (new \Swift_Message($mailtitle))
->setFrom($fromaddr)
->setTo($toaddr)
->setBody(
$this->renderView(
'security/body.html.twig', [
'url' => $mailbody,
'companyName' => $companyName,
'name' => $name,
'Usertable' => $Usertable,
]),
'text/plain');
$this->mailer->send($message);
return true;
}
/**
* @Route("/login/set_password/{hash}", name="set_password")
*/
public function passwordApproval(Request $request,$hash,UserPasswordEncoderInterface $encoder)
{
if ($this->getUser()) {
return $this->redirectToRoute('default');
}
$t = explode(" ",microtime());
$minisecond = substr((string)$t[0],2,0);
$date = date("Y-m-d H:i:s". $minisecond);
$now = new \Datetime();
$repoUsertable = $this->getDoctrine()->getRepository(Usertable::class);
$Usertable = $repoUsertable->findOneBy(['deleted' => '0','hash' => $hash]);
if(!isset($Usertable)){
return $this->redirectToRoute('app_login');
}
if($Usertable->getValidityperiod() < $now){
return $this->render('security/password_dateLater.html.twig',
array(
'Usertable' => $Usertable,
)
);
}
$user_dto = new UserPasswordDTO($Usertable);
$form = $this->createForm(UserPasswordForm::class, $user_dto);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$setUser = "system";
$em = $this->getDoctrine()->getManager();
try {
$em->beginTransaction();
$Usertable->setUpdated(new \DateTime($date));
$Usertable->setUpdatedby($setUser);
$Usertable->setDeleted(0);
$plainPassword = $user_dto->password;
$encoded = $encoder->encodePassword($Usertable, $plainPassword);
$Usertable->setPassword($encoded);
$Usertable->setHash("");
$Usertable->setValidityperiod(null);
$em->persist($Usertable);
$em->flush();
// Log記入
$array = [];
$array["userid"] = $Usertable->getId();
$array["updated"] = $Usertable->getUpdated()->format("Y/m/d H:i:s");
$array["updatedby"] = $Usertable->getUpdatedby();
$array["loginId"] = $Usertable->getLoginid();
$array["hash"] = $Usertable->getHash();
$array["validityPeriod"] = $Usertable->getValidityPeriod();
$em->getRepository(Logtable::class)->addLogs($em, $Usertable, (new \DateTime($date)), 3, $array);
$em->getConnection()->commit();
}
catch(Exception $ex)
{
$em->getConnection()->rollback();
$this->addFlash('error', 'データ登録時にエラーが発生しました');
}
return $this->redirectToRoute('app_login');
}
return $this->render('security/set_password.html.twig',
array(
'Usertable' => $Usertable,
'form' => $form->createView(),
)
);
}
}