From ab1409e108d11ce343aa3ebae7ce345ff48093af Mon Sep 17 00:00:00 2001 From: Sergio Brighenti Date: Sat, 31 Jul 2021 12:55:56 +0200 Subject: [PATCH] add support for secure cookies --- app/Web/Session.php | 3 ++- app/helpers.php | 18 ++++++++++++++---- bootstrap/app.php | 14 +++++++------- 3 files changed, 23 insertions(+), 12 deletions(-) diff --git a/app/Web/Session.php b/app/Web/Session.php index 60b853c7..5e45fef2 100644 --- a/app/Web/Session.php +++ b/app/Web/Session.php @@ -28,7 +28,7 @@ public function __construct(string $name, $path = '') $params['lifetime'], $params['path'].'; SameSite=Strict', $params['domain'], - $params['secure'], + isSecure(), $params['httponly'] ); } @@ -39,6 +39,7 @@ public function __construct(string $name, $path = '') 'cookie_httponly' => true, 'gc_probability' => 25, 'cookie_samesite' => 'Strict', // works only for php >= 7.3 + 'cookie_secure' => isSecure(), ]); if (!$started) { diff --git a/app/helpers.php b/app/helpers.php index aa56eb95..c885730a 100644 --- a/app/helpers.php +++ b/app/helpers.php @@ -93,13 +93,13 @@ function stringToBytes(string $str): float switch ($last) { case 't': $val *= 1024; - // no break + // no break case 'g': $val *= 1024; - // no break + // no break case 'm': $val *= 1024; - // no break + // no break case 'k': $val *= 1024; } @@ -528,7 +528,7 @@ function must_be_escaped($mime): bool { $mimes = [ 'text/htm', - 'image/svg' + 'image/svg', ]; foreach ($mimes as $m) { @@ -540,3 +540,13 @@ function must_be_escaped($mime): bool return false; } } + +if (!function_exists('isSecure')) { + /** + * @return bool + */ + function isSecure(): bool + { + return (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') || $_SERVER['SERVER_PORT'] === 443; + } +} diff --git a/bootstrap/app.php b/bootstrap/app.php index 4f248d30..d8299982 100644 --- a/bootstrap/app.php +++ b/bootstrap/app.php @@ -10,25 +10,25 @@ use App\Web\View; use DI\Bridge\Slim\Bridge; use DI\ContainerBuilder; -use function DI\factory; -use function DI\get; use Psr\Container\ContainerInterface as Container; use Psr\Http\Message\ServerRequestInterface as Request; use Psr\Http\Server\RequestHandlerInterface as RequestHandler; +use function DI\factory; +use function DI\get; if (!file_exists(CONFIG_FILE) && is_dir(BASE_DIR.'install/')) { header('Location: ./install/'); exit(); -} else { - if (!file_exists(CONFIG_FILE) && !is_dir(BASE_DIR.'install/')) { - exit('Cannot find the config file.'); - } +} + +if (!file_exists(CONFIG_FILE) && !is_dir(BASE_DIR.'install/')) { + exit('Cannot find the config file.'); } // Load the config $config = array_replace_recursive([ 'app_name' => 'XBackBone', - 'base_url' => isset($_SERVER['HTTPS']) ? 'https://'.$_SERVER['HTTP_HOST'] : 'http://'.$_SERVER['HTTP_HOST'], + 'base_url' => isSecure() ? 'https://'.$_SERVER['HTTP_HOST'] : 'http://'.$_SERVER['HTTP_HOST'], 'debug' => false, 'maintenance' => false, 'db' => [