214 lines
7.6 KiB
PHP
214 lines
7.6 KiB
PHP
|
|
<?php
|
|||
|
|
declare(strict_types=1);
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* Einladungen für neue Benutzerkonten.
|
|||
|
|
*
|
|||
|
|
* Der Admin legt das Konto an und erzeugt dabei einen einmaligen Link. Über
|
|||
|
|
* diesen Link vergibt der Benutzer sein Passwort selbst – es muss also kein
|
|||
|
|
* Startpasswort weitergegeben werden. Gespeichert wird nur der SHA-256-Hash
|
|||
|
|
* des Tokens; der Link ist sieben Tage gültig.
|
|||
|
|
*
|
|||
|
|
* Der Versand per E-Mail ist optional (app.mail_enabled). Ist er aus oder
|
|||
|
|
* fehlt die Adresse, zeigt die App den Link im Benutzerformular an, damit der
|
|||
|
|
* Admin ihn über einen anderen Weg weitergeben kann.
|
|||
|
|
*/
|
|||
|
|
|
|||
|
|
const DIC_INVITE_SECONDS = 7 * 86400;
|
|||
|
|
|
|||
|
|
function invite_url(string $token): string
|
|||
|
|
{
|
|||
|
|
$base = rtrim((string) config('app.public_url', ''), '/');
|
|||
|
|
return $base . url('/invite/' . $token);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/** Legt einen neuen Einladungslink an; ein älterer Link wird ungültig. */
|
|||
|
|
function invite_create(int $userId, ?int $createdBy): array
|
|||
|
|
{
|
|||
|
|
$token = bin2hex(random_bytes(32));
|
|||
|
|
$expiresAt = utc_after(DIC_INVITE_SECONDS);
|
|||
|
|
|
|||
|
|
db()->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.first_name, u.last_name, u.email, 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()]);
|
|||
|
|
$row = $stmt->fetch();
|
|||
|
|
return $row ?: null;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* Setzt Passwort und Session-Sperre für ein Konto zurück, erzeugt einen neuen
|
|||
|
|
* Einladungslink und verschickt ihn, wenn E-Mail-Versand aktiv ist.
|
|||
|
|
*
|
|||
|
|
* @return array{url: string, sent: bool, error: string, expires_at: string}
|
|||
|
|
*/
|
|||
|
|
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 {
|
|||
|
|
// Zufälliges Ersatzpasswort: das bisherige Passwort ist sofort ungültig,
|
|||
|
|
// angemeldete Geräte werden abgemeldet.
|
|||
|
|
$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;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
$invite = invite_create($userId, $createdBy);
|
|||
|
|
$result = ['url' => $invite['url'], 'sent' => false, 'error' => '', 'expires_at' => $invite['expires_at']];
|
|||
|
|
$email = trim((string) ($user['email'] ?? ''));
|
|||
|
|
|
|||
|
|
if (!mail_is_enabled()) {
|
|||
|
|
$result['error'] = 'E-Mail-Versand ist deaktiviert. Bitte den Link selbst weitergeben.';
|
|||
|
|
return $result;
|
|||
|
|
}
|
|||
|
|
if ($email === '') {
|
|||
|
|
$result['error'] = 'Für dieses Konto ist keine E-Mail-Adresse hinterlegt. Bitte den Link selbst weitergeben.';
|
|||
|
|
return $result;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
[$subject, $body] = invite_mail_text($user, $invite['url'], $invite['expires_at']);
|
|||
|
|
if (!mail_send($email, $subject, $body)) {
|
|||
|
|
$result['error'] = 'Versand an ' . $email . ' fehlgeschlagen. Bitte den Link selbst weitergeben.';
|
|||
|
|
return $result;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
$result['sent'] = true;
|
|||
|
|
return $result;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/** @return array{0: string, 1: string} Betreff und Text der Einladungs-E-Mail */
|
|||
|
|
function invite_mail_text(array $user, string $url, string $expiresAt): array
|
|||
|
|
{
|
|||
|
|
$firstName = (string) $user['first_name'];
|
|||
|
|
$loginUrl = rtrim((string) config('app.public_url', ''), '/') . url('/login');
|
|||
|
|
|
|||
|
|
$lines = [
|
|||
|
|
'Guten Tag ' . $firstName . ',',
|
|||
|
|
'',
|
|||
|
|
'für Sie wurde ein Zugang zur Terminplanung von Drink it cold angelegt.',
|
|||
|
|
'',
|
|||
|
|
'Zugang einrichten (Link sieben Tage gültig, einmal nutzbar):',
|
|||
|
|
$url,
|
|||
|
|
'',
|
|||
|
|
'Danach melden Sie sich mit Vorname, Nachname und Ihrem selbst gewählten',
|
|||
|
|
'Passwort an: ' . $loginUrl,
|
|||
|
|
'',
|
|||
|
|
'Der Link verfällt am ' . fmt_datetime($expiresAt) . '. Ist er nicht mehr gültig,',
|
|||
|
|
'wenden Sie sich bitte an den Administrator.',
|
|||
|
|
'',
|
|||
|
|
'Diese Nachricht wurde automatisch von der Terminplanung erzeugt.',
|
|||
|
|
];
|
|||
|
|
|
|||
|
|
return ['Drink it cold – Zugang zur Terminplanung', implode("\n", $lines)];
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* Vergibt das Passwort über die Einladung: Passwort speichern, Einladung
|
|||
|
|
* verbrauchen, neue Anmeldung mit diesem Konto vorbereiten.
|
|||
|
|
*/
|
|||
|
|
function invite_accept(array $invite, string $password): array
|
|||
|
|
{
|
|||
|
|
$userId = (int) $invite['user_id'];
|
|||
|
|
$pdo = db();
|
|||
|
|
$pdo->beginTransaction();
|
|||
|
|
try {
|
|||
|
|
// Einmal-Verwendung: nur wer den Eintrag als erster auf „benutzt“ setzt,
|
|||
|
|
// darf das Passwort vergeben.
|
|||
|
|
$claim = $pdo->prepare('UPDATE user_invites SET used_at = ? WHERE id = ? AND used_at IS NULL');
|
|||
|
|
$claim->execute([utc_now(), (int) $invite['id']]);
|
|||
|
|
if ($claim->rowCount() === 0) {
|
|||
|
|
$pdo->rollBack();
|
|||
|
|
throw new RuntimeException('invite_used');
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
$pdo->prepare(
|
|||
|
|
'UPDATE users SET password_hash = ?, password_changed_at = ?, updated_at = ?,
|
|||
|
|
must_change_password = 0, auth_epoch = auth_epoch + 1 WHERE id = ?'
|
|||
|
|
)->execute([hash_password($password), utc_now(), utc_now(), $userId]);
|
|||
|
|
$pdo->prepare('DELETE FROM auth_tokens WHERE user_id = ?')->execute([$userId]);
|
|||
|
|
// Weitere offene Einladungen desselben Kontos werden ungültig.
|
|||
|
|
$pdo->prepare('DELETE FROM user_invites WHERE user_id = ? AND id <> ?')->execute([$userId, (int) $invite['id']]);
|
|||
|
|
$pdo->commit();
|
|||
|
|
} catch (Throwable $error) {
|
|||
|
|
if ($pdo->inTransaction()) {
|
|||
|
|
$pdo->rollBack();
|
|||
|
|
}
|
|||
|
|
throw $error;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
$user = auth_user_by_id($userId);
|
|||
|
|
if (!$user) {
|
|||
|
|
throw new RuntimeException('Benutzer nicht gefunden.');
|
|||
|
|
}
|
|||
|
|
return $user;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/* ------------------------------------------------- Einladung nach dem Anlegen */
|
|||
|
|
|
|||
|
|
/** Merkt den Link für genau einen Seitenaufruf im Benutzerformular. */
|
|||
|
|
function invite_notice_set(int $userId, array $result): void
|
|||
|
|
{
|
|||
|
|
$_SESSION['invite_notice'] = [
|
|||
|
|
'user_id' => $userId,
|
|||
|
|
'url' => (string) $result['url'],
|
|||
|
|
'sent' => (bool) $result['sent'],
|
|||
|
|
'error' => (string) ($result['error'] ?? ''),
|
|||
|
|
'expires_at' => (string) $result['expires_at'],
|
|||
|
|
];
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
function invite_notice_take(?int $userId): ?array
|
|||
|
|
{
|
|||
|
|
$notice = $_SESSION['invite_notice'] ?? null;
|
|||
|
|
unset($_SESSION['invite_notice']);
|
|||
|
|
if (!is_array($notice) || $userId === null || (int) ($notice['user_id'] ?? 0) !== $userId) {
|
|||
|
|
return null;
|
|||
|
|
}
|
|||
|
|
return $notice;
|
|||
|
|
}
|