This commit is contained in:
2025-12-26 01:12:16 +01:00
parent c8f2dc384b
commit d9ee8b2129
5 changed files with 181 additions and 9 deletions

88
src/App/Auth.php Normal file
View File

@@ -0,0 +1,88 @@
<?php
declare(strict_types=1);
namespace App;
final class Auth
{
public function __construct(private App $app) {}
private function pdo(): \PDO
{
$pdo = $this->app->pdo();
if (!$pdo) {
throw new \RuntimeException('Database connection not available.');
}
return $pdo;
}
public function register(string $displayName, string $email, string $password): int
{
$pdo = $this->pdo();
$email = strtolower(trim($email));
$displayName = trim($displayName);
if ($displayName === '' || $email === '' || $password === '') {
throw new \InvalidArgumentException('Display-Name, E-Mail und Passwort sind erforderlich.');
}
$pdo->beginTransaction();
try {
$stmt = $pdo->prepare('SELECT id FROM users WHERE email = :email LIMIT 1');
$stmt->execute(['email' => $email]);
if ($stmt->fetchColumn()) {
throw new \RuntimeException('E-Mail ist bereits registriert.');
}
$hash = password_hash($password, PASSWORD_ARGON2ID);
$stmt = $pdo->prepare('INSERT INTO users (email, password_hash, status, created_at, updated_at) VALUES (:email, :pw, :status, NOW(), NOW())');
$stmt->execute([
'email' => $email,
'pw' => $hash,
'status' => 'active',
]);
$userId = (int)$pdo->lastInsertId();
$stmt = $pdo->prepare('INSERT INTO user_profiles (user_id, display_name, share_level, children_visibility, created_at, updated_at) VALUES (:uid, :name, :share, :childvis, NOW(), NOW())');
$stmt->execute([
'uid' => $userId,
'name' => $displayName,
'share' => 'basic',
'childvis' => 'hidden',
]);
$pdo->commit();
return $userId;
} catch (\Throwable $e) {
$pdo->rollBack();
throw $e;
}
}
public function login(string $email, string $password): int
{
$pdo = $this->pdo();
$email = strtolower(trim($email));
$stmt = $pdo->prepare('SELECT id, password_hash, status FROM users WHERE email = :email LIMIT 1');
$stmt->execute(['email' => $email]);
$row = $stmt->fetch(\PDO::FETCH_ASSOC);
if (!$row) {
throw new \RuntimeException('E-Mail oder Passwort ist falsch.');
}
if ($row['status'] !== 'active') {
throw new \RuntimeException('Account ist nicht aktiv.');
}
if (!password_verify($password, (string)$row['password_hash'])) {
throw new \RuntimeException('E-Mail oder Passwort ist falsch.');
}
$userId = (int)$row['id'];
$upd = $pdo->prepare('UPDATE users SET last_login_at = NOW() WHERE id = :id');
$upd->execute(['id' => $userId]);
return $userId;
}
}