|
1
|
|
|
<?php |
|
2
|
|
|
declare(strict_types=1); |
|
3
|
|
|
|
|
4
|
|
|
namespace SlayerBirden\DataFlowServer\Authentication\Controller; |
|
5
|
|
|
|
|
6
|
|
|
use Doctrine\ORM\EntityManager; |
|
7
|
|
|
use Doctrine\ORM\ORMException; |
|
8
|
|
|
use Psr\Http\Message\ResponseInterface; |
|
9
|
|
|
use Psr\Http\Message\ServerRequestInterface; |
|
10
|
|
|
use Psr\Http\Server\MiddlewareInterface; |
|
11
|
|
|
use Psr\Http\Server\RequestHandlerInterface; |
|
12
|
|
|
use Psr\Log\LoggerInterface; |
|
13
|
|
|
use SlayerBirden\DataFlowServer\Authentication\Entities\Token; |
|
14
|
|
|
use SlayerBirden\DataFlowServer\Doctrine\Middleware\ResourceMiddlewareInterface; |
|
15
|
|
|
use SlayerBirden\DataFlowServer\Notification\SuccessMessage; |
|
16
|
|
|
use Zend\Diactoros\Response\JsonResponse; |
|
17
|
|
|
use Zend\Hydrator\HydratorInterface; |
|
18
|
|
|
|
|
19
|
|
|
class InvalidateTokenAction implements MiddlewareInterface |
|
20
|
|
|
{ |
|
21
|
|
|
/** |
|
22
|
|
|
* @var EntityManager |
|
23
|
|
|
*/ |
|
24
|
|
|
private $entityManager; |
|
25
|
|
|
/** |
|
26
|
|
|
* @var LoggerInterface |
|
27
|
|
|
*/ |
|
28
|
|
|
private $logger; |
|
29
|
|
|
/** |
|
30
|
|
|
* @var HydratorInterface |
|
31
|
|
|
*/ |
|
32
|
|
|
private $hydrator; |
|
33
|
|
|
|
|
34
|
1 |
|
public function __construct(EntityManager $entityManager, LoggerInterface $logger, HydratorInterface $hydrator) |
|
|
|
|
|
|
35
|
|
|
{ |
|
36
|
1 |
|
$this->entityManager = $entityManager; |
|
37
|
1 |
|
$this->logger = $logger; |
|
38
|
1 |
|
$this->hydrator = $hydrator; |
|
39
|
1 |
|
} |
|
40
|
|
|
|
|
41
|
|
|
/** |
|
42
|
|
|
* @inheritdoc |
|
43
|
|
|
* @throws ORMException |
|
44
|
|
|
*/ |
|
45
|
1 |
|
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface |
|
46
|
|
|
{ |
|
47
|
|
|
/** @var Token $token */ |
|
48
|
1 |
|
$token = $request->getAttribute(ResourceMiddlewareInterface::DATA_RESOURCE); |
|
49
|
1 |
|
$token->setActive(false); |
|
50
|
|
|
|
|
51
|
1 |
|
$this->entityManager->persist($token); |
|
52
|
1 |
|
$this->entityManager->flush(); |
|
53
|
1 |
|
return new JsonResponse([ |
|
54
|
1 |
|
'data' => [ |
|
55
|
1 |
|
'token' => $this->hydrator->extract($token), |
|
56
|
|
|
], |
|
57
|
|
|
'success' => true, |
|
58
|
1 |
|
'msg' => new SuccessMessage('Token invalidated.'), |
|
59
|
1 |
|
], 200); |
|
60
|
|
|
} |
|
61
|
|
|
} |
|
62
|
|
|
|
The
EntityManagermight become unusable for example if a transaction is rolled back and it gets closed. Let’s assume that somewhere in your application, or in a third-party library, there is code such as the following:If that code throws an exception and the
EntityManageris closed. Any other code which depends on the same instance of theEntityManagerduring this request will fail.On the other hand, if you instead inject the
ManagerRegistry, thegetManager()method guarantees that you will always get a usable manager instance.