prepare('DELETE FROM user_invites WHERE user_id = ?')->execute([$userId]); db()->prepare( 'INSERT INTO user_invites (user_id, token_hash, created_by, created_at, expires_at) VALUES (?, ?, ?, ?, ?)' )->execute([$userId, hash('sha256', $token), $createdBy, utc_now(), $expiresAt]); return ['token' => $token, 'url' => invite_url($token), 'expires_at' => $expiresAt]; } /** Sucht eine offene, noch gültige Einladung zum Token. */ function invite_find(string $token): ?array { if (preg_match('/^[a-f0-9]{64}$/', $token) !== 1) { return null; } $stmt = db()->prepare( 'SELECT i.*, u.username, u.email, u.display_name, u.status FROM user_invites i JOIN users u ON u.id = i.user_id WHERE i.token_hash = ? AND i.used_at IS NULL AND i.expires_at >= ? LIMIT 1' ); $stmt->execute([hash('sha256', $token), utc_now()]); $row = $stmt->fetch(); if (!$row) { return null; } $row['id'] = (int) $row['id']; $row['user_id'] = (int) $row['user_id']; return $row; } function invite_active_for_user(int $userId): ?array { $stmt = db()->prepare( 'SELECT * FROM user_invites WHERE user_id = ? AND used_at IS NULL AND expires_at >= ? ORDER BY id DESC LIMIT 1' ); $stmt->execute([$userId, utc_now()]); return $stmt->fetch() ?: null; } function invite_redeem(string $token, string $password): void { $invite = invite_find($token); if ($invite === null) { throw new RuntimeException('invalid'); } $pdo = db(); $pdo->beginTransaction(); try { $pdo->prepare( 'UPDATE users SET password_hash = ?, password_changed_at = ?, must_change_password = 0, auth_epoch = auth_epoch + 1, updated_at = ? WHERE id = ?' )->execute([hash_password($password), utc_now(), utc_now(), (int) $invite['user_id']]); $pdo->prepare('UPDATE user_invites SET used_at = ? WHERE id = ?') ->execute([utc_now(), (int) $invite['id']]); $pdo->commit(); } catch (Throwable $error) { $pdo->rollBack(); throw $error; } } /** * Setzt das Passwort zurück, sperrt alte Sitzungen und erzeugt einen neuen * Einladungslink (Rückgabe: URL zum Weitergeben). */ function invite_provision(int $userId, ?int $createdBy): array { $user = auth_user_by_id($userId); if (!$user) { throw new RuntimeException('Benutzer nicht gefunden.'); } $pdo = db(); $pdo->beginTransaction(); try { $pdo->prepare( 'UPDATE users SET password_hash = ?, password_changed_at = ?, must_change_password = 1, auth_epoch = auth_epoch + 1, updated_at = ? WHERE id = ?' )->execute([hash_password(bin2hex(random_bytes(24))), utc_now(), utc_now(), $userId]); $pdo->prepare('DELETE FROM auth_tokens WHERE user_id = ?')->execute([$userId]); $pdo->commit(); } catch (Throwable $error) { $pdo->rollBack(); throw $error; } return invite_create($userId, $createdBy); }