Website-fabianschieder/adminer/basic_auth.php

50 lines
1.7 KiB
PHP

<?php
declare(strict_types=1);
require_once __DIR__ . '/env.php';
/**
* Basic Auth für /adminer
* Credentials aus Projekt-Root .env:
* - ADMINER_BASIC_USER
* - ADMINER_BASIC_PASS
*/
function adminer_require_basic_auth()
{
$vars = env_load(dirname(__DIR__) . '/.env');
$user = env_get($vars, 'ADMINER_BASIC_USER', '');
$pass = env_get($vars, 'ADMINER_BASIC_PASS', '');
// Wenn nicht gesetzt, sperren wir trotzdem (fail-closed), damit du es nicht aus Versehen offen lässt.
if ($user === '' || $pass === '') {
header('Content-Type: text/plain; charset=utf-8');
http_response_code(500);
echo "Basic Auth ist nicht konfiguriert.\n";
echo "Bitte setze ADMINER_BASIC_USER und ADMINER_BASIC_PASS in deiner .env.\n";
exit;
}
$givenUser = null;
$givenPass = null;
if (isset($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW'])) {
$givenUser = (string)$_SERVER['PHP_AUTH_USER'];
$givenPass = (string)$_SERVER['PHP_AUTH_PW'];
} elseif (!empty($_SERVER['HTTP_AUTHORIZATION']) && stripos((string)$_SERVER['HTTP_AUTHORIZATION'], 'basic ') === 0) {
// Fallback, falls PHP_AUTH_* nicht gesetzt wird
$decoded = base64_decode(substr((string)$_SERVER['HTTP_AUTHORIZATION'], 6));
if ($decoded !== false && strpos($decoded, ':') !== false) {
list($givenUser, $givenPass) = explode(':', $decoded, 2);
}
}
if ($givenUser === null || $givenPass === null || !hash_equals($user, $givenUser) || !hash_equals($pass, $givenPass)) {
header('WWW-Authenticate: Basic realm="DB-Verwaltung"');
header('Content-Type: text/plain; charset=utf-8');
http_response_code(401);
echo "Auth erforderlich.";
exit;
}
}