SessionAuthenticatedMiddleware   A
last analyzed

Complexity

Total Complexity 4

Size/Duplication

Total Lines 28
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 4
eloc 13
c 2
b 0
f 0
dl 0
loc 28
ccs 13
cts 13
cp 1
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A process() 0 16 3
A __construct() 0 3 1
1
<?php
2
3
/*
4
 * This file is part of the Koded package.
5
 *
6
 * (c) Mihail Binev <[email protected]>
7
 *
8
 * Please view the LICENSE distributed with this source code
9
 * for the full copyright and license information.
10
 *
11
 */
12
13
namespace Koded\Session;
14
15
use Koded\Http\{ServerResponse, StatusCode};
16
use Koded\Stdlib\Interfaces\ConfigurationFactory;
17
use Psr\Http\Message\{ResponseInterface, ServerRequestInterface};
18
use Psr\Http\Server\{MiddlewareInterface, RequestHandlerInterface};
19
use function Koded\Stdlib\json_serialize;
20
21
22
class SessionAuthenticatedMiddleware implements MiddlewareInterface
23
{
24
    public const AUTHENTICATED = 'authenticated';
25
    public const LOGIN_URI     = 'loginUri';
26
27
    private $redirectTo = '/';
28
29 4
    public function __construct(ConfigurationFactory $settings)
30
    {
31 4
        $this->redirectTo = $settings->get(self::LOGIN_URI, $this->redirectTo);
32 4
    }
33
34 3
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
35
    {
36 3
        if (true === ($_SESSION[self::AUTHENTICATED] ?? false)) {
37 1
            return $handler->handle($request);
38
        }
39
40
        // Ajax requests should be handled in the browser
41 2
        if ('XMLHTTPREQUEST' === strtoupper($_SERVER['HTTP_X_REQUESTED_WITH'] ?? '')) {
42 1
            return (new ServerResponse(json_serialize([
43 1
                'location' => $this->redirectTo,
44 1
                'status'   => StatusCode::UNAUTHORIZED
45 1
            ]), StatusCode::UNAUTHORIZED));
46
        }
47
48 1
        return (new ServerResponse(null, StatusCode::TEMPORARY_REDIRECT))
49 1
            ->withHeader('Location', $this->redirectTo);
50
    }
51
}
52