contredanse /
mfts-server
| 1 | <?php |
||
| 2 | |||
| 3 | declare(strict_types=1); |
||
| 4 | |||
| 5 | namespace App\Handler; |
||
| 6 | |||
| 7 | use App\Exception\HttpException; |
||
| 8 | use App\Service\Token\Exception\TokenValidationExceptionInterface; |
||
| 9 | use App\Service\Token\TokenManager; |
||
| 10 | use Fig\Http\Message\StatusCodeInterface; |
||
| 11 | use Psr\Http\Message\ResponseInterface; |
||
| 12 | use Psr\Http\Message\ServerRequestInterface; |
||
| 13 | use Psr\Http\Server\RequestHandlerInterface; |
||
| 14 | use Zend\Diactoros\Response\JsonResponse; |
||
| 15 | |||
| 16 | class ApiTokenValidateHandler implements RequestHandlerInterface |
||
| 17 | { |
||
| 18 | /** |
||
| 19 | * @var TokenManager |
||
| 20 | */ |
||
| 21 | private $tokenManager; |
||
| 22 | |||
| 23 | public function __construct(TokenManager $tokenManager) |
||
| 24 | { |
||
| 25 | $this->tokenManager = $tokenManager; |
||
| 26 | } |
||
| 27 | |||
| 28 | public function handle(ServerRequestInterface $request): ResponseInterface |
||
| 29 | { |
||
| 30 | $method = $request->getMethod(); |
||
| 31 | if ($method !== 'POST') { |
||
| 32 | throw new \RuntimeException('TODO - Handle error your way ;)'); |
||
| 33 | } |
||
| 34 | $body = $request->getParsedBody(); |
||
| 35 | if ($body === null) { |
||
| 36 | throw new HttpException('Empty body'); |
||
| 37 | } |
||
| 38 | /* @phpstan-ignore-next-line */ |
||
| 39 | $tokenString = array_key_exists('token', $body) ? $body['token'] : ''; |
||
|
0 ignored issues
–
show
Bug
introduced
by
Loading history...
|
|||
| 40 | |||
| 41 | try { |
||
| 42 | $token = $this->tokenManager->getValidatedToken($tokenString); |
||
| 43 | |||
| 44 | return (new JsonResponse([ |
||
| 45 | 'valid' => true, |
||
| 46 | 'data' => [ |
||
| 47 | 'user_id' => $token->getClaim('user_id'), |
||
| 48 | 'expires_at' => $token->getClaim('exp'), |
||
| 49 | 'remaining_time' => $token->getClaim('exp') - time(), |
||
| 50 | ] |
||
| 51 | ]))->withStatus(StatusCodeInterface::STATUS_OK); |
||
| 52 | } catch (TokenValidationExceptionInterface $e) { |
||
| 53 | return (new JsonResponse([ |
||
| 54 | 'valid' => false, |
||
| 55 | 'reason' => $e->getReason(), |
||
| 56 | ]))->withStatus($e->getStatusCode()); |
||
| 57 | } catch (\Throwable $e) { |
||
| 58 | return (new JsonResponse([ |
||
| 59 | 'valid' => false, |
||
| 60 | 'reason' => 'Unknown reason', |
||
| 61 | ]))->withStatus(StatusCodeInterface::STATUS_UNAUTHORIZED); |
||
| 62 | } |
||
| 63 | } |
||
| 64 | } |
||
| 65 |