freax-media/auth.php

50 lines
1.2 KiB
PHP
Raw Permalink Normal View History

<?php
// auth.php
declare(strict_types=1);
function auth_session_start(): void
{
//$secure = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off');
session_set_cookie_params([
'lifetime' => 0,
'path' => '/',
'domain' => '',
'secure' => true,
'httponly' => true,
'samesite' => 'Lax',
]);
if (session_status() !== PHP_SESSION_ACTIVE) {
session_start();
}
}
/**
* Require a valid login.
* IMPORTANT: releases the session lock immediately to avoid deadlocks/timeouts.
*/
function require_auth(bool $json = true): void
{
auth_session_start();
$ok = (isset($_SESSION['authed']) && $_SESSION['authed'] === true);
// Release the session file lock ASAP.
// This prevents other requests from blocking on session_start().
session_write_close();
if (!$ok) {
http_response_code(401);
if ($json) {
header('Content-Type: application/json; charset=utf-8');
echo json_encode(['error' => 'Unauthorized']);
} else {
header('Content-Type: text/plain; charset=utf-8');
echo "Unauthorized";
}
exit;
}
}