Files
dreamgirl/auth/auth.php
dsyoon ffcb263131 Fix auth redirects for /dreamgirl subpath
Make login/logout and redirects work when deployed under a subdirectory (e.g. /dreamgirl).

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-02-08 12:39:03 +09:00

73 lines
2.0 KiB
PHP

<?php
declare(strict_types=1);
/**
* Session-based auth gate (no DB).
* Required credentials:
* - username: admin
* - password: admin5004!
*
* NOTE: Password is stored as SHA-256 hash here (not plaintext).
*/
function dreamgirl_session_start(): void {
if (session_status() === PHP_SESSION_ACTIVE) return;
$secure = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off');
// PHP 7.3+ supports samesite via array; older versions may ignore unknown keys.
session_set_cookie_params([
'lifetime' => 0,
'path' => '/',
'httponly' => true,
'samesite' => 'Lax',
'secure' => $secure,
]);
session_start();
}
function dreamgirl_is_logged_in(): bool {
dreamgirl_session_start();
return isset($_SESSION['dreamgirl_user']) && $_SESSION['dreamgirl_user'] === 'admin';
}
function dreamgirl_check_credentials(string $username, string $password): bool {
if ($username !== 'admin') return false;
// sha256("admin5004!")
$expectedSha256 = 'adcda104b73b73f8cddf5c8047a6bc0e5e1388265ed4bf0f31f704c13cbc11b7';
$gotSha256 = hash('sha256', $password);
return hash_equals($expectedSha256, $gotSha256);
}
function dreamgirl_base_path(): string {
// If deployed under /dreamgirl, SCRIPT_NAME is like /dreamgirl/index.php
// If at web root, SCRIPT_NAME is like /index.php
$script = isset($_SERVER['SCRIPT_NAME']) ? (string)$_SERVER['SCRIPT_NAME'] : '';
$dir = rtrim(str_replace('\\', '/', dirname($script)), '/');
return ($dir === '' || $dir === '.') ? '' : $dir;
}
function dreamgirl_url(string $path): string {
$base = dreamgirl_base_path();
$p = ltrim($path, '/');
return $base . '/' . $p;
}
function dreamgirl_require_login_page(): void {
if (dreamgirl_is_logged_in()) return;
header('Location: ' . dreamgirl_url('login.php'));
exit;
}
function dreamgirl_require_login_json(): void {
if (dreamgirl_is_logged_in()) return;
http_response_code(401);
header('Content-Type: application/json; charset=utf-8');
echo json_encode(['ok' => false, 'error' => 'Unauthorized'], JSON_UNESCAPED_UNICODE);
exit;
}