Failed Conditions
Push — master ( 437f03...a35595 )
by Sébastien
02:42
created

ApiTokenValidateHandler::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
ccs 0
cts 3
cp 0
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace App\Handler;
6
7
use App\Security\ContredanseProductAccess;
8
use App\Security\Exception\NoProductAccessException;
9
use App\Security\Exception\ProductAccessExpiredException;
10
use App\Security\Exception\ProductPaymentIssueException;
11
use App\Security\UserProviderInterface;
12
use App\Service\Auth\AuthenticationManager;
13
use App\Service\Auth\Exception\AuthExceptionInterface;
14
use App\Service\Token\Exception\TokenValidationExceptionInterface;
15
use App\Service\Token\TokenManager;
16
use Fig\Http\Message\StatusCodeInterface;
17
use Psr\Http\Message\ResponseInterface;
18
use Psr\Http\Message\ServerRequestInterface;
19
use Psr\Http\Server\RequestHandlerInterface;
20
use Zend\Diactoros\Response\JsonResponse;
21
use Zend\Diactoros\Response\TextResponse;
22
23
class ApiTokenValidateHandler implements RequestHandlerInterface
24
{
25
	/**
26
     * @var TokenManager
27
     */
28
    private $tokenManager;
29
30
    public function __construct(TokenManager $tokenManager)
31
    {
32
        $this->tokenManager  = $tokenManager;
33
    }
34
35
    public function handle(ServerRequestInterface $request): ResponseInterface
36
    {
37
38
		$method = $request->getMethod();
39
		if ($method !== 'POST') {
40
			throw new \RuntimeException('TODO - Handle error your way ;)');
41
		}
42
		$body        = $request->getParsedBody();
43
		$tokenString = $body['token'] ?? '';
44
		try {
45
			$token = $this->tokenManager->getValidatedToken($tokenString);
46
47
			return (new JsonResponse([
48
				'valid' => true,
49
				'data'  => [
50
					'user_id'        => $token->getClaim('user_id'),
51
					'expires_at'     => $token->getClaim('exp'),
52
					'remaining_time' => $token->getClaim('exp') - time(),
53
				]
54
			]))->withStatus(StatusCodeInterface::STATUS_OK);
55
		} catch (TokenValidationExceptionInterface $e) {
56
			return (new JsonResponse([
57
				'valid'  => false,
58
				'reason' => $e->getReason(),
59
			]))->withStatus($e->getStatusCode());
60
		} catch (\Throwable $e) {
61
			return (new JsonResponse([
62
				'valid'  => false,
63
				'reason' => 'Unknown reason',
64
			]))->withStatus(StatusCodeInterface::STATUS_UNAUTHORIZED);
65
		}
66
67
    }
68
69
}
70