Add UserChecker to check for expired passwords, ensure users have active accounts

This commit is contained in:
Ryan Prather 2025-01-21 02:04:29 +00:00
parent 3d67d74242
commit d74e10803c

View File

@ -0,0 +1,48 @@
<?php
namespace App\Security;
use App\Entity\User as AppUser;
use DateInterval;
use DateTime;
use DateTimeZone;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Symfony\Component\Security\Core\Exception\CustomUserMessageAccountStatusException;
use Symfony\Component\Security\Core\User\UserCheckerInterface;
use Symfony\Component\Security\Core\User\UserInterface;
class UserChecker extends AbstractController implements UserCheckerInterface
{
public function checkPreAuth(UserInterface $user): void
{
if (!$user instanceof AppUser) {
return;
}
if (!$user->isActive()) {
// the message passed to this exception is meant to be displayed to the user
throw new CustomUserMessageAccountStatusException('Your user account has been deactivated by an Admin, please follow up with your Admin to reactivate it.');
}
}
public function checkPostAuth(UserInterface $user): void
{
$dt = new DateTime('now', new DateTimeZone($_ENV['COMPANY_TIMEZONE']));
$dt->sub(DateInterval::createFromDateString('120 days'));
if (!$user instanceof AppUser) {
return;
}
if (!\in_array('ROLE_USER', $user->getRoles())) {
throw new AccessDeniedException('You do not have access to this system, please contact an Admin');
}
// user account is expired, the user may be notified
if ($user->getPasswordChanged() < $dt) {
$this->addFlash('warning', 'Your password has expired. Please change it now!');
$this->redirectToRoute('app_profile');
}
}
}