Files
MyComments/src/Security/AccessTokenHandler.php
T
skylord123 7c45f64a73 - Added support for authenticating via access tokens
- update symfony to 6.4.*
- some other minor stuff
2024-02-12 23:39:11 -07:00

37 lines
1.3 KiB
PHP

<?php
namespace App\Security;
use App\Entity\UserAccessToken;
use App\Repository\UserAccessTokenRepository;
use App\Repository\UserRepository;
use Symfony\Component\Security\Core\Exception\BadCredentialsException;
use Symfony\Component\Security\Core\Exception\CredentialsExpiredException;
use Symfony\Component\Security\Http\AccessToken\AccessTokenHandlerInterface;
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\UserBadge;
class AccessTokenHandler implements AccessTokenHandlerInterface
{
public function __construct(
private UserAccessTokenRepository $repository
) {
}
public function getUserBadgeFrom(string $accessToken): UserBadge
{
/** @var $token UserAccessToken|null */
if (!$accessToken || !$token = $this->repository->findOneBy(['token' => $accessToken])) {
throw new BadCredentialsException('Invalid credentials.');
}
if($token->getDeletedAt() || ( $token->getExpiresAt() && $token->getExpiresAt() <= new \DateTime() ) ) {
throw new CredentialsExpiredException('Token expired.');
}
// and return a UserBadge object containing the user identifier from the found token
return new UserBadge($token->getOwner()->getId(), function() use($token){
return $token->getOwner();
});
}
}