src/Security/Voter/Resource/TokenRefreshVoter.php line 12

  1. <?php
  2. namespace App\Security\Voter\Resource;
  3. use Symfony\Component\Security\Core\Authorization\Voter\Voter,
  4.     Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  5. use Lexik\Bundle\JWTAuthenticationBundle\Services\JWTTokenManagerInterface;
  6. use App\DTO\TokenRefreshDTO,
  7.     App\Lib\Actions;
  8. final class TokenRefreshVoter extends Voter
  9. {
  10.     const ACTIVITY_CHECK '10 mins';
  11.     const MESSAGE 'Expired. No activity in the last ' self::ACTIVITY_CHECK;
  12.     private JWTTokenManagerInterface $jwtManager;
  13.     public function __construct(JWTTokenManagerInterface $jwtManager)
  14.     {
  15.         $this->jwtManager $jwtManager;
  16.     }
  17.     protected function supports($attribute$subject): bool
  18.     {
  19.         if (! $subject instanceof TokenRefreshDTO || Actions::VIEW !== $attribute) {
  20.             return false;
  21.         }
  22.         return true;
  23.     }
  24.     protected function voteOnAttribute($attribute$subjectTokenInterface $token): bool
  25.     {
  26.         $currentToken $this->jwtManager->decode($token);
  27.         $issuedAt = new \DateTime("@{$currentToken['iat']}");
  28.         $issuedAt->setTimezone(new \DateTimeZone(date_default_timezone_get()));
  29.         $checkFrom = new \DateTimeImmutable('-' self::ACTIVITY_CHECK);
  30.         if ($checkFrom $issuedAt) {
  31.             $checkFrom $issuedAt;
  32.         }
  33.         /** @var Admin */
  34.         $admin $token->getUser();
  35.         if ($admin->getLastActivityAt() >= $checkFrom) {
  36.             return true;
  37.         }
  38.         return false;
  39.     }
  40. }