|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
/* |
|
4
|
|
|
* This file is part of the Kreta package. |
|
5
|
|
|
* |
|
6
|
|
|
* (c) Beñat Espiña <[email protected]> |
|
7
|
|
|
* (c) Gorka Laucirica <[email protected]> |
|
8
|
|
|
* |
|
9
|
|
|
* For the full copyright and license information, please view the LICENSE |
|
10
|
|
|
* file that was distributed with this source code. |
|
11
|
|
|
*/ |
|
12
|
|
|
|
|
13
|
|
|
declare(strict_types=1); |
|
14
|
|
|
|
|
15
|
|
|
namespace Kreta\TaskManager\Tests\Double\Infrastructure\Symfony\EventListener; |
|
16
|
|
|
|
|
17
|
|
|
use Kreta\TaskManager\Infrastructure\Symfony\Security\User; |
|
18
|
|
|
use Symfony\Component\HttpFoundation\Request; |
|
19
|
|
|
use Symfony\Component\HttpKernel\Event\GetResponseEvent; |
|
20
|
|
|
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException; |
|
21
|
|
|
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface; |
|
22
|
|
|
|
|
23
|
|
|
final class DummyAuthenticationListener |
|
24
|
|
|
{ |
|
25
|
|
|
private $tokenStorage; |
|
26
|
|
|
|
|
27
|
|
|
const USER_IDS = [ |
|
28
|
|
|
'access-token-1' => 'da49c01f-2e99-45ee-9557-eb3eb57b06c5', |
|
29
|
|
|
'access-token-2' => '6704c278-e106-449f-a73d-2508e96f6177', |
|
30
|
|
|
]; |
|
31
|
|
|
|
|
32
|
|
|
public function __construct(TokenStorageInterface $tokenStorage) |
|
33
|
|
|
{ |
|
34
|
|
|
$this->tokenStorage = $tokenStorage; |
|
35
|
|
|
} |
|
36
|
|
|
|
|
37
|
|
|
public function onKernelRequest(GetResponseEvent $event) : void |
|
38
|
|
|
{ |
|
39
|
|
|
if (!$event->isMasterRequest()) { |
|
40
|
|
|
return; |
|
41
|
|
|
} |
|
42
|
|
|
$request = $event->getRequest(); |
|
43
|
|
|
|
|
44
|
|
|
// Prevents to crash the Symfony profiler routes |
|
45
|
|
|
if (0 === mb_strpos($request->getPathInfo(), '/_')) { |
|
46
|
|
|
return; |
|
47
|
|
|
} |
|
48
|
|
|
|
|
49
|
|
|
$this->tokenStorage->getToken()->setUser(new User($this->userId($request))); |
|
50
|
|
|
} |
|
51
|
|
|
|
|
52
|
|
|
private function userId(Request $request) : ?string |
|
|
|
|
|
|
53
|
|
|
{ |
|
54
|
|
|
if ($request->headers->has('Authorization')) { |
|
55
|
|
|
$token = str_replace('Bearer ', '', $request->headers->get('Authorization')); |
|
56
|
|
|
} elseif ($request->query->has('access_token')) { |
|
57
|
|
|
$token = $request->query->get('access_token'); |
|
58
|
|
|
} else { |
|
59
|
|
|
throw new UnauthorizedHttpException('Basic'); |
|
60
|
|
|
} |
|
61
|
|
|
|
|
62
|
|
|
return isset(self::USER_IDS[$token]) ? self::USER_IDS[$token] : null; |
|
63
|
|
|
} |
|
64
|
|
|
} |
|
65
|
|
|
|
Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a
@returnannotation as described here.