Completed
Push — master ( f7424d...b53e51 )
by Alejandro
07:43
created

CheckAuthenticationMiddleware::__invoke()   C

Complexity

Conditions 12
Paths 76

Size

Total Lines 68
Code Lines 45

Duplication

Lines 16
Ratio 23.53 %

Code Coverage

Tests 33
CRAP Score 13.4171

Importance

Changes 0
Metric Value
cc 12
eloc 45
nc 76
nop 3
dl 16
loc 68
ccs 33
cts 42
cp 0.7856
crap 13.4171
rs 5.7751
c 0
b 0
f 0

1 Method

Rating   Name   Duplication   Size   Complexity  
A CheckAuthenticationMiddleware::createTokenErrorResponse() 0 13 1

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
namespace Shlinkio\Shlink\Rest\Middleware;
3
4
use Acelaya\ZsmAnnotatedServices\Annotation\Inject;
5
use Fig\Http\Message\StatusCodeInterface;
6
use Interop\Http\ServerMiddleware\DelegateInterface;
7
use Interop\Http\ServerMiddleware\MiddlewareInterface;
8
use Psr\Http\Message\ResponseInterface as Response;
9
use Psr\Http\Message\ServerRequestInterface as Request;
10
use Psr\Log\LoggerInterface;
11
use Psr\Log\NullLogger;
12
use Shlinkio\Shlink\Rest\Authentication\JWTService;
13
use Shlinkio\Shlink\Rest\Authentication\JWTServiceInterface;
14
use Shlinkio\Shlink\Rest\Exception\AuthenticationException;
15
use Shlinkio\Shlink\Rest\Util\RestUtils;
16
use Zend\Diactoros\Response\JsonResponse;
17
use Zend\Expressive\Router\RouteResult;
18
use Zend\I18n\Translator\TranslatorInterface;
19
use Zend\Stdlib\ErrorHandler;
20
21
class CheckAuthenticationMiddleware implements MiddlewareInterface, StatusCodeInterface
22
{
23
    const AUTHORIZATION_HEADER = 'Authorization';
24
25
    /**
26
     * @var TranslatorInterface
27
     */
28
    private $translator;
29
    /**
30
     * @var JWTServiceInterface
31
     */
32
    private $jwtService;
33
    /**
34
     * @var LoggerInterface
35
     */
36
    private $logger;
37
38
    /**
39
     * CheckAuthenticationMiddleware constructor.
40
     * @param JWTServiceInterface|JWTService $jwtService
41
     * @param TranslatorInterface $translator
42
     * @param LoggerInterface $logger
43
     *
44
     * @Inject({JWTService::class, "translator", "Logger_Shlink"})
45
     */
46 6
    public function __construct(
47
        JWTServiceInterface $jwtService,
48
        TranslatorInterface $translator,
49
        LoggerInterface $logger = null
50
    ) {
51 6
        $this->translator = $translator;
52 6
        $this->jwtService = $jwtService;
53 6
        $this->logger = $logger ?: new NullLogger();
54 6
    }
55
56
    /**
57
     * Process an incoming server request and return a response, optionally delegating
58
     * to the next middleware component to create the response.
59
     *
60
     * @param Request $request
61
     * @param DelegateInterface $delegate
62
     *
63
     * @return Response
64
     */
65 6
    public function process(Request $request, DelegateInterface $delegate)
66
    {
67
        // If current route is the authenticate route or an OPTIONS request, continue to the next middleware
68
        /** @var RouteResult $routeResult */
69 6
        $routeResult = $request->getAttribute(RouteResult::class);
70 6
        if (! isset($routeResult)
71 6
            || $routeResult->isFailure()
72 6
            || $routeResult->getMatchedRouteName() === 'rest-authenticate'
73 6
            || $request->getMethod() === 'OPTIONS'
74 6
        ) {
75 1
            return $delegate->process($request);
76
        }
77
78
        // Check that the auth header was provided, and that it belongs to a non-expired token
79 5
        if (! $request->hasHeader(self::AUTHORIZATION_HEADER)) {
80 1
            return $this->createTokenErrorResponse();
81
        }
82
83
        // Get token making sure the an authorization type is provided
84 4
        $authToken = $request->getHeaderLine(self::AUTHORIZATION_HEADER);
85 4
        $authTokenParts = explode(' ', $authToken);
86 4 View Code Duplication
        if (count($authTokenParts) === 1) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
87 1
            return new JsonResponse([
88 1
                'error' => RestUtils::INVALID_AUTHORIZATION_ERROR,
89 1
                'message' => sprintf($this->translator->translate(
90
                    'You need to provide the Bearer type in the %s header.'
91 1
                ), self::AUTHORIZATION_HEADER),
92 1
            ], self::STATUS_UNAUTHORIZED);
93
        }
94
95
        // Make sure the authorization type is Bearer
96 3
        list($authType, $jwt) = $authTokenParts;
97 3 View Code Duplication
        if (strtolower($authType) !== 'bearer') {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
98 1
            return new JsonResponse([
99 1
                'error' => RestUtils::INVALID_AUTHORIZATION_ERROR,
100 1
                'message' => sprintf($this->translator->translate(
101
                    'Provided authorization type %s is not supported. Use Bearer instead.'
102 1
                ), $authType),
103 1
            ], self::STATUS_UNAUTHORIZED);
104
        }
105
106
        try {
107 2
            ErrorHandler::start();
108 2
            if (! $this->jwtService->verify($jwt)) {
109 1
                return $this->createTokenErrorResponse();
110
            }
111 1
            ErrorHandler::stop(true);
112
113
            // Update the token expiration and continue to next middleware
114 1
            $jwt = $this->jwtService->refresh($jwt);
115 1
            $response = $delegate->process($request);
116
117
            // Return the response with the updated token on it
118 1
            return $response->withHeader(self::AUTHORIZATION_HEADER, 'Bearer ' . $jwt);
119
        } catch (AuthenticationException $e) {
120
            $this->logger->warning('Tried to access API with an invalid JWT.' . PHP_EOL . $e);
121
            return $this->createTokenErrorResponse();
122
        } finally {
123 2
            ErrorHandler::clean();
124
        }
125
    }
126
127 2
    protected function createTokenErrorResponse()
128
    {
129 2
        return new JsonResponse([
130 2
            'error' => RestUtils::INVALID_AUTH_TOKEN_ERROR,
131 2
            'message' => sprintf(
132 2
                $this->translator->translate(
133
                    'Missing or invalid auth token provided. Perform a new authentication request and send provided '
134
                    . 'token on every new request on the "%s" header'
135 2
                ),
136
                self::AUTHORIZATION_HEADER
137 2
            ),
138 2
        ], self::STATUS_UNAUTHORIZED);
139
    }
140
}
141