black-sheep-bluff/app/Services/AuthService.php
2026-09-18 06:46:56 +02:00

39 lines
1 KiB
PHP

<?php
declare(strict_types=1);
/** Auth-Helfer (1:1 aus auth.php): Session-Pruefung, Admin-Gate, Public-User-DTO. */
final class AuthService
{
public static function requireAuth(PDO $pdo): array
{
if (empty($_SESSION['user_id'])) {
respond(['error' => 'Nicht eingeloggt.'], 401);
}
$stmt = $pdo->prepare('SELECT id, username, avatar, role FROM gtl_users WHERE id = ?');
$stmt->execute([$_SESSION['user_id']]);
$user = $stmt->fetch();
if (!$user) {
session_destroy();
respond(['error' => 'Session ungültig.'], 401);
}
return $user;
}
public static function requireAdmin(PDO $pdo): void
{
$user = self::requireAuth($pdo);
if ($user['role'] !== 'admin') {
respond(['error' => 'Keine Berechtigung.'], 403);
}
}
public static function publicUser(array $row): array
{
return [
'id' => (int) $row['id'],
'username' => $row['username'],
'avatar' => $row['avatar'] ?? null,
'role' => $row['role'],
];
}
}