Files
netwatch/app/lib/auth.php
2026-02-16 13:56:01 +01:00

62 lines
1.3 KiB
PHP

<?php
/**
* app/lib/auth.php
*
* Single-user authentication helpers.
*/
function isAuthenticated(): bool
{
if (!defined('AUTH_REQUIRED') || AUTH_REQUIRED === false) {
return true;
}
return isset($_SESSION['auth']) && $_SESSION['auth'] === true;
}
function login(string $password): bool
{
$hash = defined('ADMIN_PASSWORD_HASH') ? trim((string)ADMIN_PASSWORD_HASH) : '';
if ($hash === '') {
return false;
}
if (password_verify($password, $hash)) {
$_SESSION['auth'] = true;
$_SESSION['auth_at'] = time();
return true;
}
return false;
}
function logout(): void
{
unset($_SESSION['auth'], $_SESSION['auth_at']);
if (session_status() === PHP_SESSION_ACTIVE) {
session_regenerate_id(true);
}
}
function requireAuth(): void
{
if (!defined('AUTH_REQUIRED') || AUTH_REQUIRED === false) {
return;
}
if (!isAuthenticated()) {
$isApiRequest = str_starts_with($_SERVER['REQUEST_URI'] ?? '', '/api/');
if ($isApiRequest) {
http_response_code(401);
header('Content-Type: application/json');
echo json_encode(['error' => 'Nicht authentifiziert']);
exit;
}
$target = defined('LOGIN_PATH') ? LOGIN_PATH : '/login.php';
header('Location: ' . $target);
exit;
}
}