Files
cmasa/app/Middleware/SecurityHeaders.php
2026-10-29 13:34:31 +07:00

70 lines
2.2 KiB
PHP

<?php
/*******************************************************************
PHP Class : /Middleware/SecurityHeaders
Description : Control User Sesion dan CSP
Created By : Siau Pheng ([email protected]).
Created Date : December 7th, 2008.
Last Modified : October 20th, 2026.
(c) 3FONIA Software; WWW.3FONIA.COM.
*******************************************************************/
declare(strict_types=1);
namespace App\Middleware;
use flight\Engine;
use flight\Session;
use Webapp\App\Register;
use Tracy\Debugger;
class SecurityHeaders {
protected Engine $app;
protected Session $session;
public function __construct(Engine $app, Session $session) {
$this->app = $app;
$this->session = $session;
}
public function before(): void {
$url = $this->app->request()->url;
// check if slash on end url
if ($url !== '/' && substr($url, -1) === '/') {
$clean_url = rtrim($url, '/');
$this->app->redirect($clean_url, 301);
}
// check register
if (Register::reg_check($this->session)) {
if (!$this->app->user()->logged() && !str_ends_with($url, '/login') && !str_contains($url, 'monitor') && !str_contains($url, '/cache')) {
$this->app->redirect('login', 307);
$this->app->stop();
}
} else {
if (!str_ends_with($url, '/401')) {
$this->session->delete('WEB_APP');
$this->app->redirect('401', 308);
$this->app->stop();
}
}
// security
$nonce = $this->app->get('csp_nonce');
$tracyCssBypass = (Debugger::$showBar === true) ? '\'unsafe-inline\'' : "'nonce-{$nonce}'";
$this->app->response()->header('X-Frame-Options', 'SAMEORIGIN');
$this->app->response()->header("Content-Security-Policy", "default-src 'self'; script-src 'self' 'nonce-{$nonce}'; style-src 'self' {$tracyCssBypass}; img-src 'self' data:; connect-src 'self' ws://localhost:* wss://localhost:*");
$this->app->response()->header('X-XSS-Protection', '1; mode=block');
$this->app->response()->header('X-Content-Type-Options', 'nosniff');
$this->app->response()->header('Referrer-Policy', 'no-referrer-when-downgrade');
$this->app->response()->header('Strict-Transport-Security', 'max-age=31536000; includeSubDomains; preload');
$this->app->response()->header('Permissions-Policy', 'geolocation=()');
}
}