<?php
namespace App\Controller;
use App\Entity\CBRCResetPassword;
use App\Entity\CBRCUser;
use App\Form\Type\AddUserRoleType;
use App\Form\Type\ResetPassword1Type;
use App\Form\Type\ResetPassword2Type;
use App\Utilities\Secure;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Form\FormError;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use App\Utilities\Mail;
class SecurityController extends AbstractController
{
/**
* @Route("/connexion", name="app_login")
*/
public function login(AuthenticationUtils $authenticationUtils): Response
{
/*if ($this->getUser()) {
return $this->redirectToRoute('home');
}*/
// 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]);
}
/**
* @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("/admin/acces", name="app_accessmanager")
*/
public function ShowAccessManager(Request $request)
{
$this->denyAccessUnlessGranted('ROLE_ADMIN');
$adminusers = $this->getDoctrine()->getRepository(CBRCUser::class)->findByRole('ROLE_ADMIN');
$writterusers = $this->getDoctrine()->getRepository(CBRCUser::class)->findByRole('ROLE_WRITER');
$formaddrole = $this->createForm(AddUserRoleType::class);
$formaddrole->handleRequest($request);
if($formaddrole->isSubmitted() && $formaddrole->isValid())
{
$email=$formaddrole->get('email')->getData();
$role = $formaddrole->get('role')->getData();
$user= $this->getDoctrine()->getRepository(CBRCUser::class)->findOneBy(['email'=>$email]);
if($user==null) {
$this->addFlash('danger', 'L\'utilisateur n\'existe pas');
return $this->redirect($request->getUri());
}
$user->setRoles(array($role));
$em=$this->getDoctrine()->getManager();
$em->persist($user);
$em->flush();
return $this->redirect($request->getUri());
}
if ($formaddrole->isSubmitted() && !$formaddrole->isValid()) {
foreach ($formaddrole->getErrors(true) as $error)
$this->addFlash('danger', "(" . $error->getOrigin()->getName() . ") " . $error->getMessage());
$formaddrole->clearErrors(true);
}
return $this->render('security/adminaccessmanager.html.twig',[
'adminusers' => $adminusers,
'writterusers' => $writterusers,
'formrole' => $formaddrole->createView(),
'idactive' => 7
]);
}
/**
* @Route("/security/resetpassword" , name="app_resetpassword")
*/
public function ResetPassword(Request $request)
{
$formreset = $this->createForm(ResetPassword1Type::class);
$formreset->handleRequest($request);
if($formreset->isSubmitted() && $formreset->isValid()){
$email=$formreset->getData()['email'];
//get the user
$user=$this->getDoctrine()->getRepository(CBRCUser::class)->findOneBy(array('email'=>$email));
if($user==null)
{
$formreset->get('email')->addError(new FormError('Email inconnu'));
}
else
{
$this->ClearUserResetPassword($user);
$datetime = new \DateTime();
$datetime->add(new \DateInterval("P1D")); //add 1day
$resetpassword = new CBRCResetPassword();
$resetpassword->setUser($user);
$resetpassword->setToken($this->GetUniqueToken());
$resetpassword->setValiditydate($datetime);
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($resetpassword);
$entityManager->flush($resetpassword);
//Send mail
$link = $this->generateUrl('app_resetpassword_token', ['token'=>$resetpassword->getToken()], UrlGeneratorInterface::ABSOLUTE_URL);
$txtmessage = "Pour reinitialier votre mot de passe rendez vous sur: ".$link;
$subject = "Reinitialiser le mot de passe";
$htmlmessage = $this->render('mail/resetpasswordmail.html.twig', [
'subject' => $subject,
'link' => $link,
]);
$return = Mail::SendMailToMail($email, $subject, $htmlmessage, $txtmessage);
if($return ==false)
{
$this->addFlash('danger', 'Erreur lors de l\'envoi du mail');
}
return $this->render('security/resetpasswordconfirmation.html.twig', [
'passwordchanged' => false,
]);
}
}
if($formreset->isSubmitted() && !$formreset->isValid())
{
foreach($formreset->getErrors(true) as $error)
$this->addFlash('danger', "(".$error->getOrigin()->getName().") ".$error->getMessage());
return $this->redirect($request->getUri());
}
return $this->render('security/resetpassword.html.twig', [
'formreset' => $formreset->createView(),
]);
}
/**
* @Route("/security/resetpassword/{token}", name="app_resetpassword_token")
*/
public function ResetPasswordWithToken($token, Request $request, UserPasswordEncoderInterface $passwordEncoder)
{
$resetpassword = $this->getDoctrine()->getRepository(CBRCResetPassword::class)->findOneBy(array('token'=>$token));
$entityManager = $this->getDoctrine()->getManager();
if($resetpassword->getValiditydate()< new \DateTime())
{
$entityManager->remove($resetpassword);
$entityManager->flush();
$resetpassword=null;
}
if($resetpassword==null)
{
return $this->redirectToRoute("app_resetpassword");
}
$formreset = $this->createForm(ResetPassword2Type::class);
$formreset->handleRequest($request);
if($formreset->isSubmitted() && $formreset->isValid()){
$email=$formreset->getData()['email'];
$user=$resetpassword->getUser();
//check email with bfresetpassworduser email
if($email != $resetpassword->getUser()->getEmail())
{
$formreset->get('email')->addError(new FormError('Email inconnu'));
}
else
{
$password = $passwordEncoder->encodePassword($user, $formreset->getData()['plainPassword']);
$user->setPassword($password);
// 4) save the User!
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($user);
$entityManager->flush();
//remove the resetpasswordrequest
$entityManager->remove($resetpassword);
$entityManager->flush();
return $this->render('security/resetpasswordconfirmation.html.twig', [
'passwordchanged' => true,
]);
}
}
if($formreset->isSubmitted() && !$formreset->isValid())
{
foreach($formreset->getErrors(true) as $error)
$this->addFlash('danger', "(".$error->getOrigin()->getName().") ".$error->getMessage());
return $this->redirect($request->getUri());
}
return $this->render('security/resetpassword.html.twig', [
'formreset' => $formreset->createView(),
]);
}
/**
* @Route ("/security/account/removerole/{role}/{userid}", name="app_removeuserrole")
*/
public function RemoveRoleFromUser(string $role, int $userid)
{
$this->denyAccessUnlessGranted('ROLE_ADMIN');
$user= $this->getDoctrine()->getRepository(CBRCUser::class)->find($userid);
if(!$user)
throw new NotFoundHttpException();
$roles = $user->getRoles();
if (($key = array_search($role, $roles)) !== false) {
unset($roles[$key]);
}
$user->setRoles($roles);
$em = $this->getDoctrine()->getManager();
$em->persist($user);
$em->flush();
$this->addFlash('success', 'Les accès ont été retirés à l\'utilisateur');
return $this->redirectToRoute('app_accessmanager');
}
/**
* @Route ("/security/account/superadmin/setdefault", name="app_superadmin_setdefault")
*/
public function SetDefaultSuperAdmin(Request $request): \Symfony\Component\HttpFoundation\RedirectResponse
{
$this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');
//Check if there is an role_super_admin in the database
$userrepository =$this->getDoctrine()->getRepository(CBRCUser::class);
$superadmins = $userrepository->findByRole('ROLE_SUPER_ADMIN');
if(count($superadmins)<=1)
{
//set the first user
$firstuser = $userrepository->findFirst();
$firstuser->setRoles(array('ROLE_SUPER_ADMIN'));
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($firstuser);
$entityManager->flush();
$this->addFlash('primary', 'Super admin role add default');
}
return $this->redirectToRoute('account');
}
/**
* @Route ("/security/account/superadmin/add/{email}", name="app_superadmin_add")
*/
public function AddSuperAdmin($email, Request $request): \Symfony\Component\HttpFoundation\RedirectResponse
{
$this->denyAccessUnlessGranted('ROLE_SUPER_ADMIN');
//Check if there is an role_super_admin in the database
$user =$this->getDoctrine()->getRepository(CBRCUser::class)->findOneBy(['email'=>$email]);
if($user!=null)
{
//set the first user
$user->setRoles(array('ROLE_SUPER_ADMIN'));
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($user);
$entityManager->flush();
$this->addFlash('primary', 'Super admin role add');
}
return $this->redirectToRoute('account');
}
/**
* @Route ("/security/account/superadmin/remove/{email}", name="app_superadmin_remove")
*/
public function RemoveSuperAdmin($email, Request $request): \Symfony\Component\HttpFoundation\RedirectResponse
{
$this->denyAccessUnlessGranted('ROLE_SUPER_ADMIN');
//Check if there is an role_super_admin in the database
$user =$this->getDoctrine()->getRepository(CBRCUser::class)->findOneBy(['email'=>$email]);
if($user!=null)
{
//set the first user
$user->setRoles(array(''));
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($user);
$entityManager->flush();
$this->addFlash('primary', 'Super admin role remove');
}
return $this->redirectToRoute('account');
}
private function ClearUserResetPassword(CBRCUser $user)
{
//get bfreset from user id
$resetpassword = $this->getDoctrine()->getRepository(CBRCResetPassword::class)->findOneBy(['user'=>$user]);
if($resetpassword!=null)
{
$entityManager = $this->getDoctrine()->getManager();
$entityManager->remove($resetpassword);
$entityManager->flush();
}
}
private function GetUniqueToken()
{
$randomstring="";
$unique=false;
$resetrepository = $this->getDoctrine()->getRepository(CBRCResetPassword::class);
while(!$unique)
{
$randomstring = Secure::GenerateKey(20);
$resetpassword = $resetrepository->findOneBy(array('token'=>$randomstring));
$unique=($resetpassword==null);
}
return $randomstring;
}
}