<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
use App\Service\ResetPasswordService;
use App\Entity\User;
use App\Service\UserService;
class ResetPasswordController extends AbstractController
{
/**
* @Route("/dealer/first-access-request", name="dealer_first_access_request", methods={"POST"})
*/
public function dealerFirstAccessRequest(Request $request, ResetPasswordService $resetPasswordService, UserService $userService): Response
{
$data = json_decode($request->getContent(), true);
if (!isset($data['id'])) {
return $this->JsonErrorResponse('Utente non trovato');
}
$user = $resetPasswordService->getUserById($data['id']);
if(!$user){
return $this->JsonErrorResponse('Utente non trovato');
}
$userService->sendNewDealerUserEmail($user);
if($userService->hasErrors()){
return $this->JsonErrorResponse('Errore invio richiesta e-mail');
}
return $this->JsonOkResponse();
}
/**
* @Route("/dealer/reset-password-request", name="dealer_reset_password_request", methods={"POST"})
*/
public function dealerResetPasswordRequest(Request $request, ResetPasswordService $resetPasswordService): Response
{
$data = json_decode($request->getContent(), true);
if (!isset($data['id'])) {
return $this->JsonErrorResponse('Utente non trovato');
}
$user = $resetPasswordService->getUserById($data['id']);
if(!$user){
return $this->JsonErrorResponse('Utente non trovato');
}
$result = $resetPasswordService->sendResetPasswordEmail($user);
if ($result != true) {
return $this->JsonErrorResponse('Errore invio richiesta e-mail');
}
return $this->JsonOkResponse();
}
/**
* @Route("/reset-password", name="reset_password", methods={"GET", "POST"})
*/
public function resetPassword(Request $request, ResetPasswordService $resetPasswordService): Response
{
//rotta per gestire il reset della password da parte dell'utente in autonomia
$user = $this->get('security.token_storage')->getToken()->getUser();
if($user instanceof User){
//effettua il logout manuale
$this->get('security.token_storage')->setToken(null);
$request->getSession()->invalidate();
}
$email = null;
$error = null;
$showForm = true;
if($request->getMethod() == 'POST'){
try {
$authUsername = $request->request->get('auth_username');
if(!$authUsername){
throw new \RuntimeException('Inserire un indirizzo email o un numero di partita IVA valido.');
}
$isEmail = filter_var($authUsername, FILTER_VALIDATE_EMAIL);
if ($isEmail) {
$email = $authUsername;
$user = $resetPasswordService->getUserByEmail($email);
}else{
$user = $resetPasswordService->getUserByAuthUsername($authUsername);
}
if(!$user){
throw new \RuntimeException('Utente non trovato.');
}
$emailSent = $resetPasswordService->sendResetPasswordEmail($user, $email);
if(!$emailSent){
throw new \RuntimeException('Errore invio richiesta e-mail');
}
$showForm = false;
} catch (\Exception $e) {
$error = $e->getMessage();
}
}
//rotta pubblica per il cambio password dell'utente in autonomia
return $this->render('reset-password-email.html.twig', [
'email' => $email ?: '',
'error' => $error,
'showForm' => $showForm
]);
}
/**
* @Route("/reset-password-form", name="reset_password_form", methods={"GET"})
*/
public function resetPasswordForm(Request $request, ResetPasswordService $resetPasswordService): Response
{
$error = null;
$showForm = true;
$code = $request->query->get('c');
if (!$code) {
$error = 'La richiesta di ripristino password non è valida.<br>Controlla il link corretto nella email.';
$showForm = false;
}
if(!$error){
$user = $resetPasswordService->getUserByResetCode($code);
if (!$user) {
//errore generico utente non trovato
$error = 'La richiesta di cambio password non è valida.<br>Effettuare una nuova richiesta.';
$showForm = false;
}
}
if(!$error){
//check scadenza richiesta password
$resetPasswordDate = $user->getResetPasswordDate();
$now = new \DateTime();
$passwordDateValid = $resetPasswordDate->diff($now)->days <= 1;
if(!$passwordDateValid){
$error = 'La richiesta di ripristino password è scaduta. Devi effettuare una nuova richiesta.';
$showForm = false;
}
}
return $this->render('reset-password-form.html.twig', [
'showForm' => $showForm,
'code' => $code,
'error' => $error,
]);
}
/**
* @Route("/reset-password-submit", name="reset_password_submit",methods={"POST"})
*/
public function resetPasswordSubmit(Request $request, ResetPasswordService $resetPasswordService): Response
{
$code = $request->request->get('code');
$password = $request->request->get('password');
$passwordConfirm = $request->request->get('password_confirm');
if(!$code){
throw $this->createNotFoundException('404');
}
$error = null;
$showForm = true;
if($password != $passwordConfirm){
$error = 'La conferma password non corrisponde. Inserisci nuovamente la password.';
}
if(!$error){
$checkPassword = $resetPasswordService->checkPassword($password);
if($checkPassword['valid'] == false){
//$error = implode('<br>', $checkPassword['errors']);
$error = 'La password non rispetta i requisiti di sicurezza.';
}
}
if(!$error){
$resetPasswordService->saveNewPassword($code, $password);
$showForm = false;
//forza logout utente
$user = $this->get('security.token_storage')->getToken()->getUser();
if($user instanceof User){
//effettua il logout manuale
$this->get('security.token_storage')->setToken(null);
$request->getSession()->invalidate();
}
}
return $this->render('reset-password-form.html.twig', [
'showForm' => $showForm,
'code' => $code,
'error' => $error,
]);
}
/**
* @Route("/partner/reset-password", name="partner_reset_password", methods={"POST"})
*/
public function partnerResetPassword(Request $request, ResetPasswordService $resetPasswordService): Response
{
//cambio password dal profilo dell'utente partner
try {
$user = $this->get('security.token_storage')->getToken()->getUser();
if(!$user){
throw new \RuntimeException('Utente non trovato.');
}
$sent = $resetPasswordService->sendResetPasswordEmail($user);
if($sent != true){
throw new \RuntimeException('Errore invio richiesta e-mail.');
}
} catch (\Exception $e) {
return $this->JsonErrorResponse($e->getMessage());
}
return $this->JsonOkResponse();
}
private function JsonOkResponse($data = [])
{
return new Response(json_encode([
'result' => 'OK',
'data' => $data,
'errmsg' => '',
]));
}
private function JsonErrorResponse($errmsg)
{
$json = json_encode([
'result' => 'ERROR',
'errmsg' => $errmsg,
]);
$response = new Response($json);
$response->setStatusCode(500);
return $response;
}
}