<?php
namespace App\Controller;
use App\Entity\Users;
use App\Entity\Roles;
use App\Repository\UsersRepository;
use App\Repository\RolesRepository;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use App\Form\ResetPasswordRequestFormType;
use App\Form\RegistrationFormType;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use Symfony\Contracts\Translation\TranslatorInterface;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Mime\Email;
use Doctrine\ORM\EntityManagerInterface;
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
class SecurityController extends AbstractController
{
private $rolesRepository;
private $em;
private $UsersRepository;
public function __construct(EntityManagerInterface $em, UserPasswordHasherInterface $userPasswordHasher, UsersRepository $UsersRepository, RolesRepository $rolesRepository, Security $security)
{
$this->security = $security;
$this->em = $em;
$this->rolesRepository = $rolesRepository;
$this->UsersRepository = $UsersRepository;
}
#[Route(path: '/checklogin', name: 'app_check_login')]
public function checklogin(Security $security, AuthenticationUtils $authenticationUtils): Response
{
$user = $security->getUser();
if (!$user) {
return $this->redirectToRoute('app_login');
}
$userRole = $user->getUserRole();
if (!$userRole) {
return $this->redirectToRoute('app_index');
}
$roles = $userRole->getRoles();
if ($roles == 'CLIENT') {
return $this->redirectToRoute('app_client');
}
return $this->redirectToRoute('app_index');
}
#[Route(path: '/createclient', name: 'app_create_client')]
public function createclient(Request $request,UserPasswordHasherInterface $userPasswordHasher,EntityManagerInterface $em): Response
{
$flag = 0;
$user = new Users();
$form = $this->createForm(RegistrationFormType::class, $user);
$form->handleRequest($request);
$now = new \DateTimeImmutable();
if ($form->isSubmitted() && $form->isValid()) {
$token = substr(md5(openssl_random_pseudo_bytes(20)), -10);
$user->setTokens($token);
$email = $user->getUsername();
try {
$mail = new PHPMailer(true);
$mail->CharSet = 'UTF-8';
$mail->isSMTP();
$mail->Host = 'sosconsultoria.pt';
$mail->SMTPAuth = true;
$mail->Username = 'suporte@sosconsultoria.pt';
$mail->Password = $_SERVER['MAILER_PASSWORD'];
$mail->SMTPSecure = 'ssl';
$mail->Port = 465;
$mail->setFrom('suporte@sosconsultoria.pt', 'SOS Consultoria');
$mail->addAddress($email);
$mail->addReplyTo('suporte@sosconsultoria.pt', 'SOS Consultoria');
$mail->isHTML(true);
$mail->Subject = 'Tickets Central';
$mail->Body = '
<table style="font-family: Helvetica, Arial, sans-serif; font-size: 14px;">
<tr><td><strong>Tickets Central</strong></td></tr>
<tr><td>Por favor confirme o seu e-mail clicando no link abaixo:</td></tr>
<tr><td><a href="https://helpdesk.sosadvanced.pt/logint/' . $token . '" style="color: #608E34; font-weight: bold;">Confirmar e-mail</a></td></tr>
<tr><td>— <b>Tickets</b> - Admin Dashboard</td></tr>
</table>';
$mail->send();
} catch (MailException $e) {
return new Response('Erro ao enviar e-mail: ' . $mail->ErrorInfo);
}
$user->setPassword(
$userPasswordHasher->hashPassword(
$user,
$form->get('plainPassword')->getData()
)
);
$user->setPhoto('default.png');
$user->setActive(1);
$user->setUpdatedAt($now);
$user->setCreatedAt($now);
$userRole = $this->rolesRepository->find(4);
$user->setUserRole($userRole);
$em->persist($user);
$em->flush();
$flag = 1;
return $this->redirectToRoute('app_confirm');
}
return $this->render('client_area/security/register.html.twig', [
'registrationForm' => $form->createView(),
'flag' => $flag,
]);
}
#[Route(path: '/login', name: 'app_login')]
public function login(AuthenticationUtils $authenticationUtils): Response
{
$error = $authenticationUtils->getLastAuthenticationError();
$lastUsername = $authenticationUtils->getLastUsername();
return $this->render('security/login.html.twig', ['username' => $lastUsername, 'error' => $error]);
}
#[Route(path: '/logout', name: 'app_logout')]
public function logout(): void
{
throw new \LogicException();
}
#[Route(path: '/logint/{token}', name: 'app_login_with_token')]
public function loginwithtoken($token, AuthenticationUtils $authenticationUtils): Response
{
if($UsersRepository = $this->UsersRepository->findbyToken($token)){
foreach($UsersRepository as $Users){
$userusername = $Users['username'];
$userid = $Users['id'];
}
$UserL = $this->UsersRepository->removetoken($userid);
return $this->redirectToRoute('app_login');
}else{
return $this->redirectToRoute('app_home');
}
/* $UsersRepository = $this->UsersRepository->findbyToken($token);
foreach($UsersRepository as $Users){
$userusername = $Users['username'];
$userid = $Users['id'];
}
if(!isset($userusername)){return $this->redirectToRoute('app_login');}
if($_POST){
$UserL = $this->UsersRepository->removetoken($userid);
return $this->redirectToRoute('app_check_login');
}
$error = $authenticationUtils->getLastAuthenticationError();
$lastUsername = $authenticationUtils->getLastUsername(); */
return $this->render('security/login.html.twig', ['last_username' => $lastUsername, 'error' => $error, 'username' => $userusername]);
}
#[Route('/resetpassword', methods:['GET','POST'], name: 'app_reset_password')]
public function register(Request $request, UserPasswordHasherInterface $userPasswordHasher, EntityManagerInterface $entityManager): Response
{
$flag = 0;
if (isset($_POST["email"])) {
$email = $_POST["email"];
$users = $this->UsersRepository->findbyEmail($email);
if (!$users) {
return new Response("Utilizador não encontrado.", 404);
}
foreach ($users as $user1) {
$userid = $user1["id"];
}
$token = substr(md5(openssl_random_pseudo_bytes(20)), -10);
$user = $this->UsersRepository->find($userid);
$user->setTokens($token);
try {
$mail = new PHPMailer(true);
$mail->CharSet = 'UTF-8';
$mail->isSMTP();
$mail->Host = 'sosconsultoria.pt';
$mail->SMTPAuth = true;
$mail->Username = 'suporte@sosconsultoria.pt';
$mail->Password = $_SERVER['MAILER_PASSWORD'];
$mail->SMTPSecure = 'ssl';
$mail->Port = 465;
$mail->setFrom('suporte@sosconsultoria.pt', 'SOS Consultoria');
$mail->addAddress($email);
$mail->addReplyTo('suporte@sosconsultoria.pt', 'SOS Consultoria');
$mail->isHTML(true);
$mail->Subject = 'Tickets Central - Recuperação de Password';
$mail->Body = '
<table style="font-family: Helvetica, Arial, sans-serif; font-size: 14px;">
<tr><td><strong>Tickets Central</strong></td></tr>
<tr><td>Por favor clique no link abaixo para alterar a sua password:</td></tr>
<tr><td><a href="https://helpdesk.sosadvanced.pt/newpassword/' . $token . '" style="color: #608E34; font-weight: bold;">Alterar Password</a></td></tr>
<tr><td>— <b>Tickets</b> - Admin Dashboard</td></tr>
</table>
';
$mail->send();
} catch (MailException $e) {
return new Response('Erro ao enviar e-mail: ' . $mail->ErrorInfo);
}
$entityManager->persist($user);
$entityManager->flush();
$flag = 1;
return $this->render('reset_password/check_email.html.twig', [
'email' => $email,
]);
}
return $this->render('reset_password/request.html.twig');
}
#[Route(path: '/newpassword/{token}',methods:['GET','POST'], name: 'app_newpassword')]
public function newpassword($token, Request $request, UserPasswordHasherInterface $userPasswordHasher, EntityManagerInterface $entityManager): Response
{
if(isset($_POST["newpassword"]))
{
$user = new Users;
$UsersRepository = $this->UsersRepository->findbyToken($token);
foreach($UsersRepository as $Users){
$username=$Users['username'];
$userid = $Users['id'];
}
$user=$this->UsersRepository->find($userid);
$user->setPassword(
$userPasswordHasher->hashPassword(
$user,
$_POST['newpassword']
)
);
$entityManager->persist($user);
$entityManager->flush();
$user = $this->UsersRepository->removetoken($userid);
return $this->redirectToRoute('app_login',[
]);
}
return $this->render('reset_password/reset.html.twig', [
'token'=>$token,
]);
}
#[Route(path: '/password/{token}',methods:['GET','POST'], name: 'app_createpassword')]
public function createpassword($token, Request $request, UserPasswordHasherInterface $userPasswordHasher, EntityManagerInterface $entityManager): Response
{
if(isset($_POST["choosepassword"]))
{
$user = new Users;
$UsersRepository = $this->UsersRepository->findbyToken($token);
foreach($UsersRepository as $Users){
$username=$Users['username'];
$userid = $Users['id'];
}
$user=$this->UsersRepository->find($userid);
$user->setPassword(
$userPasswordHasher->hashPassword(
$user,
$_POST['choosepassword']
)
);
$entityManager->persist($user);
$entityManager->flush();
$user = $this->UsersRepository->removetoken($userid);
return $this->redirectToRoute('app_login',[
]);
}
return $this->render('reset_password/enterpassword.html.twig', [
'token'=>$token,
]);
}
}