58 lines
1.4 KiB
PHP
58 lines
1.4 KiB
PHP
<?php
|
|
require_once __DIR__ . '/../config.php';
|
|
|
|
define('AUTH_PASSWD_FILE', __DIR__ . '/../auth.passwd');
|
|
|
|
/**
|
|
* Returns the active password hash.
|
|
* auth.passwd (written by the web interface) takes precedence over
|
|
* the UI_PASS_HASH constant in config.php.
|
|
*/
|
|
function active_pass_hash(): string {
|
|
if (is_readable(AUTH_PASSWD_FILE)) {
|
|
return trim(file_get_contents(AUTH_PASSWD_FILE));
|
|
}
|
|
return UI_PASS_HASH;
|
|
}
|
|
|
|
function auth_enabled(): bool {
|
|
return active_pass_hash() !== '';
|
|
}
|
|
|
|
function require_login(): void {
|
|
if (!auth_enabled()) {
|
|
return;
|
|
}
|
|
if (session_status() === PHP_SESSION_NONE) {
|
|
session_start();
|
|
}
|
|
if (empty($_SESSION['authenticated'])) {
|
|
header('Location: login.php');
|
|
exit;
|
|
}
|
|
}
|
|
|
|
function attempt_login(string $username, string $password): bool {
|
|
if (!auth_enabled()) {
|
|
return true;
|
|
}
|
|
return $username === UI_USER && password_verify($password, active_pass_hash());
|
|
}
|
|
|
|
function logout(): void {
|
|
if (session_status() === PHP_SESSION_NONE) {
|
|
session_start();
|
|
}
|
|
$_SESSION = [];
|
|
session_destroy();
|
|
}
|
|
|
|
/**
|
|
* Hash $new_password and write it to auth.passwd.
|
|
* Returns true on success, false if the file could not be written.
|
|
*/
|
|
function save_password(string $new_password): bool {
|
|
$hash = password_hash($new_password, PASSWORD_DEFAULT);
|
|
return file_put_contents(AUTH_PASSWD_FILE, $hash . PHP_EOL, LOCK_EX) !== false;
|
|
}
|