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