<?php
namespace App\Package\Admin\Main\Controller\Login;
use App\Package\Toolkit\RouteLocalizer\RouteLocalizer;
use Symfony\Component\HttpFoundation\{Request, Response};
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
use Symfony\Component\Security\Core\Exception\TooManyLoginAttemptsAuthenticationException;
/**
* LoginController
*
* Performs login and is admin still logged action (for auto logging out)
*
* @author Symfony
* @author Daniel Balowski <d.balowski@openform.pl> (_refactorer, _developer)
* @copyright Openform
* @since 03.2019
*/
class LoginController extends AbstractController
{
/** @var \Psr\Container\ContainerInterface */
protected $container;
/** @var RouteLocalizer */
private $routeLocalizer;
public function __construct(RouteLocalizer $routeLocalizer)
{
$this->routeLocalizer = $routeLocalizer;
}
/**
* Performs login
*
* @param Request $request
*
* @return Response
*/
public function loginAction(
Request $request,
AuthenticationUtils $authenticationUtils,
AuthorizationCheckerInterface $authChecker,
TokenStorageInterface $tokenStorage
): Response
{
// $authChecker = $this->get('security.authorization_checker'); //deprec
// $tokenStorage = $this->get('security.token_storage'); //deprec
if (
$tokenStorage->getToken() &&
$authChecker->isGranted('ROLE_ADMIN')
) {
return $this->redirect(
$this->routeLocalizer->generate('admin_adminModule_home', [], $request->getLocale())
);
}
$error = $authenticationUtils->getLastAuthenticationError();
$lastUsername = $authenticationUtils->getLastUsername();
if ($error instanceof TooManyLoginAttemptsAuthenticationException) {
/** @var TooManyLoginAttemptsAuthenticationException $error */
$error->errorCode = 13666;
}
return $this->render(
'@admin_templates/Login/login.html.twig',
[
'lastUsername' => $lastUsername,
'error' => $error,
]
);
}
/**
* [AJAX] Checks if admin is still logged
*
* @param Request $request
*
* @return Response
*/
public function isAdminStillLoggedAction(Request $request): Response
{
/** @var \App\Package\Admin\Main\Entity\Admin */
$admin = $this->getUser();
if (
!$admin ||
gettype($admin) === 'string' ||
!$lastSeen = $admin->getLastSeen()
) {
return new Response(
json_encode(
['status' => 'logout']
)
);
}
$lastSeen =
(clone $lastSeen)
->modify('+' . $this->container->getParameter('admin.login.session_minutes') . 'mins');
$now = new \DateTime();
$timeLeft = strtotime($lastSeen->format('Y-m-d H:i:s')) - strtotime($now->format('Y-m-d H:i:s'));
if ($timeLeft <= 0) {
return new Response(
json_encode(
['status' => 'logout']
)
);
}
return new Response(
json_encode(
[
'status' => 'still_logged',
'minutes_left' => $minutes = floor($timeLeft / 60),
'seconds_left' => $timeLeft - ($minutes * 60)
]
)
);
}
}