diff --git a/config/routes.yaml b/config/routes.yaml index 774bbff..aa67fd3 100644 --- a/config/routes.yaml +++ b/config/routes.yaml @@ -40,6 +40,15 @@ api_v1_login: method: POST _format: json +api_v1_logout: + path: /api/v1/logout + controller: App\Api\V1\Controller\SecurityController::logout + defaults: + _format: json + requirements: + method: GET + _format: json + api_v1_torrents: path: /api/v1/torrents controller: App\Api\V1\Controller\TorrentController::search diff --git a/src/Api/V1/Controller/SecurityController.php b/src/Api/V1/Controller/SecurityController.php index 7f123db..58f7e85 100644 --- a/src/Api/V1/Controller/SecurityController.php +++ b/src/Api/V1/Controller/SecurityController.php @@ -4,8 +4,10 @@ namespace App\Api\V1\Controller; use App\Entity\{ApiToken, User}; use App\Repository\{ApiTokenRepository, UserRepository}; +use App\Security\Token\AuthenticatedApiToken; use Doctrine\ORM\EntityManagerInterface; use Symfony\Component\HttpFoundation\{JsonResponse, Request}; +use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface; use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface; class SecurityController extends AbstractApiController @@ -40,4 +42,30 @@ class SecurityController extends AbstractApiController return $this->createJsonResponse($apiToken->getKey()); } + + public function logout(TokenStorageInterface $tokenStorage, ApiTokenRepository $apiTokenRepo, EntityManagerInterface $em): JsonResponse + { + $token = $tokenStorage->getToken(); + + if (!$token instanceof AuthenticatedApiToken) { + return $this->createJsonResponse(null,[],JsonResponse::HTTP_INTERNAL_SERVER_ERROR, 'Invalid session token type retrieved.'); + } + if (null === $apiTokenKey = $token->getTokenKey()) { + return $this->createJsonResponse(null,[],JsonResponse::HTTP_INTERNAL_SERVER_ERROR, 'Can\'t retrieve token key from session.'); + } + + if (null === $apiToken = $apiTokenRepo->findOneBy(['key' => $apiTokenKey])) { + return $this->createJsonResponse(null,[],JsonResponse::HTTP_INTERNAL_SERVER_ERROR, 'API token with such key not found in the database.'); + } + + $em->remove($apiToken); + + try { + $em->flush(); + } catch (\Exception $ex) { + return $this->createJsonResponse(null,[],JsonResponse::HTTP_INTERNAL_SERVER_ERROR, 'API token deauthentication failure.'); + } + + return $this->createJsonResponse(null,[],JsonResponse::HTTP_OK, 'Successfully logged out.'); + } } \ No newline at end of file