#2 API logout implemented.

This commit is contained in:
Alexey Skobkin 2018-06-27 02:15:39 +03:00
parent 61405ead60
commit 6dec613b61
2 changed files with 37 additions and 0 deletions

View File

@ -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

View File

@ -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.');
}
}