Added auth support and a helper script, targeting frankenphp
This commit is contained in:
parent
8f545c3f67
commit
0783e08fe9
8 changed files with 655 additions and 4 deletions
50
auth.php
Normal file
50
auth.php
Normal file
|
|
@ -0,0 +1,50 @@
|
|||
<?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;
|
||||
}
|
||||
}
|
||||
|
||||
Loading…
Add table
Add a link
Reference in a new issue