Completed
Push — master ( 178a08...5c0b6f )
by Oleg
05:22
created

TokenMiddleware   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 69
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 7

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 11
lcom 1
cbo 7
dl 0
loc 69
ccs 36
cts 36
cp 1
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
B process() 0 37 8
A getToken() 0 14 2
1
<?php
2
declare(strict_types=1);
3
4
namespace SlayerBirden\DataFlowServer\Authentication\Middleware;
5
6
use Doctrine\Common\Collections\Criteria;
7
use Doctrine\ORM\EntityManager;
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 SlayerBirden\DataFlowServer\Authentication\Entities\Token;
13
use SlayerBirden\DataFlowServer\Notification\DangerMessage;
14
use Zend\Diactoros\Response\JsonResponse;
15
use Zend\Expressive\Router\RouteResult;
16
17
class TokenMiddleware implements MiddlewareInterface
18
{
19
    const USER_PARAM = 'currentUser';
20
    /**
21
     * @var EntityManager
22
     */
23
    private $entityManager;
24
25 61
    public function __construct(EntityManager $entityManager)
0 ignored issues
show
Bug introduced by
You have injected the EntityManager via parameter $entityManager. This is generally not recommended as it might get closed and become unusable. Instead, it is recommended to inject the ManagerRegistry and retrieve the EntityManager via getManager() each time you need it.

The EntityManager might 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:

function someFunction(ManagerRegistry $registry) {
    $em = $registry->getManager();
    $em->getConnection()->beginTransaction();
    try {
        // Do something.
        $em->getConnection()->commit();
    } catch (\Exception $ex) {
        $em->getConnection()->rollback();
        $em->close();

        throw $ex;
    }
}

If that code throws an exception and the EntityManager is closed. Any other code which depends on the same instance of the EntityManager during this request will fail.

On the other hand, if you instead inject the ManagerRegistry, the getManager() method guarantees that you will always get a usable manager instance.

Loading history...
26
    {
27 61
        $this->entityManager = $entityManager;
28 61
    }
29
30
    /**
31
     * @inheritdoc
32
     */
33 61
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
34
    {
35 61
        $authorization = $request->getHeader('Authorization');
36 61
        if (empty($authorization)) {
37 1
            return new JsonResponse([
38 1
                'data' => [],
39
                'success' => false,
40 1
                'msg' => new DangerMessage('Empty Authorization header. Access denied.'),
41 1
            ], 401);
42
        }
43 60
        $token = $this->getToken(reset($authorization));
0 ignored issues
show
Security Bug introduced by
It seems like reset($authorization) targeting reset() can also be of type false; however, SlayerBirden\DataFlowSer...nMiddleware::getToken() does only seem to accept string, did you maybe forget to handle an error condition?
Loading history...
44 60
        if (!$token || !$token->isActive() || ($token->getDue() < new \DateTime())) {
45 3
            return new JsonResponse([
46 3
                'data' => [],
47
                'success' => false,
48 3
                'msg' => new DangerMessage('Token is absent or invalid. Access denied.'),
49 3
            ], 401);
50
        }
51
        // check ACL
52 57
        $routeResult = $request->getAttribute(RouteResult::class, false);
53 57
        if (false === $routeResult) {
54
            // Can not perform ACL check
55 1
            return $handler->handle($request);
56
        }
57 56
        $routeName = $routeResult->getMatchedRouteName();
58 56
        foreach ($token->getGrants() as $grant) {
59 56
            if ($grant->getResource() === $routeName) {
60 56
                return $handler->handle($request->withAttribute(self::USER_PARAM, $token->getOwner()));
61
            }
62
        }
63
64 1
        return new JsonResponse([
65 1
            'data' => [],
66
            'success' => false,
67 1
            'msg' => new DangerMessage('The permission to resource is not granted.'),
68 1
        ], 403);
69
    }
70
71 60
    private function getToken(string $authorization): ?Token
72
    {
73 60
        $token = str_replace('Bearer ', '', $authorization);
74 60
        $tokens = $this->entityManager
75 60
            ->getRepository(Token::class)
76 60
            ->matching(
77 60
                Criteria::create()->where(Criteria::expr()->eq('token', $token))
78
            );
79 60
        if ($tokens->count()) {
80 59
            return $tokens->first();
81
        }
82
83 1
        return null;
84
    }
85
}
86