<?php
namespace App\Controller\Admin;
use App\Security\AdminUser;
use App\Service\AdminService;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Exception\UserNotFoundException;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
class LoginController extends AbstractController
{
/**
* @Route("/login", name="app_login")
*/
public function index(AuthenticationUtils $authenticationUtils, Request $request, AdminService $admin): Response
{
// if already auth redirect do homepage
$test=$admin->getAdminUserFromSession($request);
if($test instanceof AdminUser)
{
return $this->redirectToRoute("admin_index");
}
// get the login error if there is one
//$error = $authenticationUtils->getLastAuthenticationError();
$error='';
$lastUsername='';
// last username entered by the user
//$lastUsername = $authenticationUtils->getLastUsername();
if($request->isMethod('POST'))
{
$username = $request->request->get('_username');
$lastUsername=$username;
$password = $request->request->get('_password');
try
{
$user=$admin->loginUserAndCreateSessionData($username, $password);
}
catch(UserNotFoundException $th)
{
$error="Login failed, check your username and password";
}
catch(\Throwable $th)
{
//throw new UserNotFoundException();
//$error="Login faiol;ed, check your username and password".$th->getMessage();
//$error="Login failed, check your username and password";
$error="Login failed: ".$th->getMessage();
}
if(!strlen($error))
{
return $this->redirectToRoute("admin_index");
}
}
return $this->render('admin/login/index.html.twig', [
'last_username' => $lastUsername,
'error' => $error,
//'controller_name' => 'LoginController',
]);
}
/**
* @Route("/logout", name="app_logout")
*/
public function logout(AuthenticationUtils $authenticationUtils, Request $request, AdminService $admin): Response
{
$admin->logoutAdminUser($request);
return $this->redirectToRoute("app_login");
}
}