|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Jidaikobo\Kontiki\Middleware; |
|
4
|
|
|
|
|
5
|
|
|
use Jidaikobo\Kontiki\Core\Auth; |
|
6
|
|
|
use Psr\Http\Message\ResponseInterface as Response; |
|
7
|
|
|
use Psr\Http\Message\ServerRequestInterface as Request; |
|
8
|
|
|
use Psr\Http\Server\MiddlewareInterface; |
|
9
|
|
|
use Psr\Http\Server\RequestHandlerInterface; |
|
10
|
|
|
use Slim\Views\PhpRenderer; |
|
11
|
|
|
use Slim\Routing\RouteParser; |
|
12
|
|
|
|
|
13
|
|
|
class AuthMiddleware implements MiddlewareInterface |
|
14
|
|
|
{ |
|
15
|
|
|
private array $excludedRoutes = [ |
|
16
|
|
|
'/favicon.ico', |
|
17
|
|
|
'/login', |
|
18
|
|
|
'/logout', |
|
19
|
|
|
]; |
|
20
|
|
|
|
|
21
|
|
|
public function __construct( |
|
22
|
|
|
private PhpRenderer $view, |
|
23
|
|
|
private Auth $auth, |
|
24
|
|
|
private RouteParser $routeParser, |
|
25
|
|
|
) {} |
|
26
|
|
|
|
|
27
|
|
|
public function process(Request $request, RequestHandlerInterface $handler): Response |
|
28
|
|
|
{ |
|
29
|
|
|
$requestedPath = $request->getUri()->getPath(); |
|
30
|
|
|
$path = '/' . basename($requestedPath); |
|
31
|
|
|
|
|
32
|
|
|
// for guest routes |
|
33
|
|
|
if (in_array($path, $this->excludedRoutes, true)) { |
|
34
|
|
|
return $handler->handle($request); |
|
35
|
|
|
} |
|
36
|
|
|
|
|
37
|
|
|
// for login users |
|
38
|
|
|
if (!$this->auth->isLoggedIn()) { |
|
39
|
|
|
$redirect = substr($requestedPath, strlen(env('BASEPATH', ''))); |
|
40
|
|
|
$loginUrl = $this->routeParser->urlFor('login', [], ['redirect' => $redirect]); |
|
41
|
|
|
|
|
42
|
|
|
// Check the referrer and redirect to login as it is an internal transition |
|
43
|
|
|
$referer = $request->getHeaderLine('Referer'); |
|
44
|
|
|
if (strpos($referer, $_SERVER['HTTP_HOST']) !== false) { |
|
45
|
|
|
return (new \Slim\Psr7\Response()) |
|
46
|
|
|
->withHeader('Location', $loginUrl) |
|
47
|
|
|
->withStatus(302); |
|
48
|
|
|
} |
|
49
|
|
|
|
|
50
|
|
|
// If an external access is suspected, return 404. |
|
51
|
|
|
$response = new \Slim\Psr7\Response(); |
|
52
|
|
|
$content = $this->view->fetch('error/404.php'); |
|
53
|
|
|
return $this->view->render( |
|
54
|
|
|
$response->withHeader('Content-Type', 'text/html')->withStatus(404), |
|
55
|
|
|
'layout-error.php', |
|
56
|
|
|
[ |
|
57
|
|
|
'lang' => env('APPLANG', 'en'), |
|
58
|
|
|
'pageTitle' => __('404_text'), |
|
59
|
|
|
'content' => $content |
|
60
|
|
|
] |
|
61
|
|
|
); |
|
62
|
|
|
} |
|
63
|
|
|
|
|
64
|
|
|
return $handler->handle($request); |
|
65
|
|
|
} |
|
66
|
|
|
} |
|
67
|
|
|
|