73 lines
2.4 KiB
PHP
73 lines
2.4 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace ModulesCore;
|
|
|
|
use App\AccountGate;
|
|
use App\ConfigLoader;
|
|
use App\KeycloakAuth;
|
|
|
|
final class ModuleHttp
|
|
{
|
|
public static function requireDesktopAccess(string $projectRoot, bool $json = false): void
|
|
{
|
|
$auth = new KeycloakAuth(ConfigLoader::load($projectRoot, 'keycloak'));
|
|
$accountGate = new AccountGate(ConfigLoader::load($projectRoot, 'registration'));
|
|
$hasAuthenticatedSession = $auth->ensureAuthenticatedSession();
|
|
|
|
if ($hasAuthenticatedSession) {
|
|
$currentUser = is_array($_SESSION['desktop_auth']['user'] ?? null) ? $_SESSION['desktop_auth']['user'] : [];
|
|
$accountCheck = $accountGate->checkUsername((string) ($currentUser['username'] ?? ''));
|
|
|
|
if (!($accountCheck['allowed'] ?? false)) {
|
|
$auth->logout();
|
|
$message = (string) ($accountCheck['message'] ?? 'Dieses Konto ist noch nicht freigeschaltet.');
|
|
|
|
if ($json) {
|
|
self::respondJson(['error' => $message], 403);
|
|
}
|
|
|
|
$target = (string) ($accountCheck['state'] ?? '') === 'pending'
|
|
? '/auth/pending/?username=' . urlencode((string) ($currentUser['username'] ?? ''))
|
|
: '/auth/inactive/?message=' . urlencode($message);
|
|
header('Location: ' . $target, true, 302);
|
|
exit;
|
|
}
|
|
}
|
|
|
|
if (!$hasAuthenticatedSession && !$auth->shouldShowDesktop()) {
|
|
if ($json) {
|
|
self::respondJson(['error' => 'Nicht autorisiert.'], 401);
|
|
}
|
|
|
|
header('Location: /auth/keycloak', true, 302);
|
|
exit;
|
|
}
|
|
}
|
|
|
|
public static function currentUserScope(): string
|
|
{
|
|
$auth = $_SESSION['desktop_auth'] ?? null;
|
|
|
|
if (!is_array($auth)) {
|
|
return 'guest';
|
|
}
|
|
|
|
$user = is_array($auth['user'] ?? null) ? $auth['user'] : [];
|
|
|
|
return (string) ($user['sub'] ?? $user['username'] ?? 'guest');
|
|
}
|
|
|
|
/**
|
|
* @param array<string, mixed> $payload
|
|
*/
|
|
private static function respondJson(array $payload, int $statusCode): never
|
|
{
|
|
http_response_code($statusCode);
|
|
header('Content-Type: application/json; charset=utf-8');
|
|
echo json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
|
|
exit;
|
|
}
|
|
}
|