Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 14
0.00% covered (danger)
0.00%
0 / 3
CRAP
0.00% covered (danger)
0.00%
0 / 1
RequireToken
0.00% covered (danger)
0.00%
0 / 14
0.00% covered (danger)
0.00%
0 / 3
42
0.00% covered (danger)
0.00%
0 / 1
 __construct
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 __invoke
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
6
 getTokenFromHeader
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
12
1<?php
2/** @noinspection PhpUnhandledExceptionInspection */
3declare(strict_types=1);
4// TODO unit test
5
6use Slim\Exception\HttpUnauthorizedException;
7use Psr\Http\Server\RequestHandlerInterface as RequestHandler;
8use Slim\Http\ServerRequest as Request;
9
10class RequireToken {
11  protected array $requiredTypes = [];
12
13  public function __construct(string ...$requiredTypes) {
14    $this->requiredTypes = $requiredTypes;
15  }
16
17  function __invoke(Request $request, RequestHandler $handler) {
18    if ($request->isOptions()) {
19      return $handler->handle($request);
20    }
21
22    $tokenString = $this->getTokenFromHeader($request);
23    $sessionDAO = new SessionDAO();
24    $token = $sessionDAO->getToken($tokenString, $this->requiredTypes);
25    $request = $request->withAttribute('AuthToken', $token);
26    return $handler->handle($request);
27  }
28
29  function getTokenFromHeader(Request $request): string {
30    if (!$request->hasHeader('AuthToken')) {
31      throw new HttpUnauthorizedException($request, 'Auth Header not sufficient: missing');
32    }
33
34    $authToken = $request->getHeaderLine('AuthToken');
35
36    if (!$authToken) {
37      throw new HttpUnauthorizedException($request, "Auth Header not sufficient: empty");
38    }
39
40    return $authToken;
41  }
42}