ReadAttributeString('SelectedAccount'); $account = $this->accounts()[$id] ?? []; $catalog = $this->accessCatalog(); $level = ['type' => 'Select', 'options' => [['caption' => 'Nur ansehen', 'value' => 'view'], ['caption' => 'Ansehen und bedienen', 'value' => 'control']]]; $grants = function (string $name, string $caption, array $options, array $values): array { return ['type' => 'List', 'name' => $name, 'caption' => $caption, 'rowCount' => 5, 'add' => true, 'delete' => true, 'values' => $values, 'columns' => $this->planGrantColumns($options, $values)]; }; $userForm = ['type' => 'ExpansionPanel', 'caption' => 'Benutzer und Zugriffsrechte', 'expanded' => true, 'items' => [ ['type' => 'ValidationTextBox', 'caption' => 'Direkter Zugang (an die Symcon-Adresse anhängen)', 'value' => '/hook/' . $this->hookPath() . '/', 'enabled' => false], ['type' => 'Button', 'caption' => 'Anmeldeseite öffnen', 'link' => true, 'onClick' => 'echo NFSC_OpenLogin($id);'], ['type' => 'Select', 'name' => 'AccountSelect', 'caption' => 'Benutzer auswählen', 'value' => $id, 'options' => $this->accountOptions(), 'onChange' => 'NFSC_SelectAccessUser($id, $AccountSelect);'], ['type' => 'ValidationTextBox', 'name' => 'AccountName', 'caption' => 'Benutzername', 'value' => $account['name'] ?? ''], ['type' => 'PasswordTextBox', 'name' => 'AccountPassword', 'caption' => 'Neues Passwort (leer = bestehendes behalten)', 'value' => ''], ['type' => 'Button', 'name' => 'AccountReset', 'caption' => 'Passwort zurücksetzen', 'enabled' => $id !== '', 'onClick' => 'echo NFSC_ResetUserPassword($id, $AccountSelect, $AccountPassword);'], ['type' => 'CheckBox', 'name' => 'AccountEnabled', 'caption' => 'Zugang aktiv', 'value' => $account['enabled'] ?? true], ['type' => 'Select', 'name' => 'AccountRole', 'caption' => 'Rolle', 'value' => $account['role'] ?? 'user', 'options' => [['caption' => 'Benutzer · Ansicht und freigegebene Bedienung', 'value' => 'user'], ['caption' => 'Admin · vollständiger Zugriff und Editor', 'value' => 'admin']]], ['type' => 'CheckBox', 'name' => 'AccountViewAll', 'caption' => 'Alle Zustände ansehen', 'value' => $account['view_all'] ?? false], ['type' => 'CheckBox', 'name' => 'AccountControlAll', 'caption' => 'Alles ansehen und bedienen', 'value' => $account['control_all'] ?? false], $grants('AccountRooms', 'Einzelne Räume', $catalog['rooms'], $account['rooms'] ?? []), $grants('AccountDevices', 'Einzelne Geräte im Plan', $catalog['devices'], $account['devices'] ?? []), ['type' => 'List', 'name' => 'AccountObjects', 'caption' => 'Weitere Symcon-Geräte / Datenpunkte (optional)', 'rowCount' => 4, 'add' => true, 'delete' => true, 'values' => $account['objects'] ?? [], 'columns' => [['name' => 'target', 'caption' => 'Objekt aus dem Objektbaum', 'width' => 'auto', 'add' => 0, 'edit' => ['type' => 'SelectObject']], ['name' => 'access', 'caption' => 'Recht', 'width' => '190px', 'add' => 'view', 'edit' => $level]]], ['type' => 'Button', 'caption' => 'Benutzer speichern', 'onClick' => [ // Native List variables implement iteration/ArrayAccess; direct JSON encoding does not serialize their rows. '$rooms = []; foreach ($AccountRooms as $row) { $rooms[] = ["target" => $row["target"], "access" => $row["access"]]; }', '$devices = []; foreach ($AccountDevices as $row) { $devices[] = ["target" => $row["target"], "access" => $row["access"]]; }', '$objects = []; foreach ($AccountObjects as $row) { $objects[] = ["target" => $row["target"], "access" => $row["access"]]; }', 'echo NFSC_SaveAccessUser($id, $AccountSelect, $AccountName, $AccountRole, $AccountEnabled, $AccountViewAll, $AccountControlAll, json_encode($rooms), json_encode($devices), json_encode($objects), $AccountPassword);', ]], ['type' => 'Button', 'name' => 'AccountRevoke', 'caption' => 'Benutzer abmelden', 'enabled' => $id !== '', 'onClick' => 'echo NFSC_RevokeUserSessions($id, $AccountSelect);'], ['type' => 'Button', 'name' => 'AccountDelete', 'caption' => 'Benutzer löschen', 'enabled' => $id !== '', 'confirm' => 'Diesen NextFloor-Benutzer einschließlich seiner Zugänge löschen?', 'onClick' => 'echo NFSC_DeleteAccessUser($id, $AccountSelect);'], ['type' => 'PopupButton', 'caption' => 'ⓘ Rechte und Passwörter', 'popup' => ['caption' => 'Zugriffsrechte', 'items' => [ ['type' => 'Label', 'caption' => 'Die Auswahl eines Benutzers lädt dessen Einstellungen und alle drei Freigabetabellen. Änderungen werden erst durch Benutzer speichern übernommen; beim Wechsel werden nicht gespeicherte Eingaben verworfen. Das Passwortfeld wird bei jedem Wechsel geleert.'], ['type' => 'Label', 'caption' => 'Admins dürfen den Editor und alle Geräte verwenden. Die Benutzerverwaltung bleibt ausschließlich in der Symcon-Konfiguration.'], ['type' => 'Label', 'caption' => 'Alle Zustände ansehen ohne weitere Bedienfreigabe ist ein Zugang nur zum Lesen. Einzelne Raum- und Gerätefreigaben ergänzen diese Grundrechte. Ohne Freigabe bleibt das Gebäude sichtbar, seine Zustände werden nicht übertragen.'], ['type' => 'Label', 'caption' => 'Eine Raumfreigabe umfasst seine verknüpften Werte, Geräte im Raum und die zugeordneten Bereichskategorien. Gerätefreigaben gelten für deren verknüpfte Datenpunkte. Bei automatischen Gerätezuordnungen die benötigten Symcon-Objekte zusätzlich auswählen oder feste Verknüpfungen im Editor setzen.'], ['type' => 'Label', 'caption' => 'Passwörter: 8–72 Bytes. Leer beim Speichern erhält das bisherige Passwort. Änderungen an Konto oder Rechten beenden bestehende Anmeldungen dieses Benutzers. Die Konsole kann jederzeit Passwörter zurücksetzen.'], ]]], ]]; $form['actions'][] = $userForm; return json_encode($form, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR); } public function OpenLogin(): string { $this->requireWebHook(); return 'link:/hook/' . $this->hookPath() . '/login'; } private function accountOptions(): array { $options = [['caption' => '+ Neuen Benutzer anlegen', 'value' => '']]; foreach ($this->accounts() as $id => $a) $options[] = ['caption' => $a['name'] . ($a['enabled'] ? '' : ' (gesperrt)'), 'value' => $id]; return $options; } private function planGrantColumns(array $options, array $values): array { foreach ($values as $v) if (!in_array($v['target'], array_column($options, 'value'), true)) $options[] = ['caption' => '(Nicht mehr im Plan) ' . $v['target'], 'value' => $v['target']]; return [['name' => 'target', 'caption' => 'Freigabe', 'width' => 'auto', 'add' => '', 'edit' => ['type' => 'Select', 'options' => [['caption' => 'Bitte auswählen', 'value' => ''], ...$options]]], ['name' => 'access', 'caption' => 'Recht', 'width' => '190px', 'add' => 'view', 'edit' => ['type' => 'Select', 'options' => [['caption' => 'Nur ansehen', 'value' => 'view'], ['caption' => 'Ansehen und bedienen', 'value' => 'control']]]]]; } public function SelectAccessUser(string $UserID): void { $a = $this->accounts()[$UserID] ?? []; if (!$a) $UserID = ''; $this->WriteAttributeString('SelectedAccount', $UserID); $catalog = $this->accessCatalog(); $this->UpdateFormField('AccountSelect', 'options', json_encode($this->accountOptions())); foreach (['AccountSelect' => $UserID, 'AccountName' => $a['name'] ?? '', 'AccountEnabled' => $a['enabled'] ?? true, 'AccountRole' => $a['role'] ?? 'user', 'AccountViewAll' => $a['view_all'] ?? false, 'AccountControlAll' => $a['control_all'] ?? false, 'AccountPassword' => ''] as $name => $value) $this->UpdateFormField($name, 'value', $value); foreach (['AccountRooms' => 'rooms', 'AccountDevices' => 'devices', 'AccountObjects' => 'objects'] as $name => $key) { if ($key !== 'objects') $this->UpdateFormField($name, 'columns', json_encode($this->planGrantColumns($catalog[$key], $a[$key] ?? []))); $this->UpdateFormField($name, 'values', json_encode($a[$key] ?? [])); } foreach (['AccountReset', 'AccountRevoke', 'AccountDelete'] as $name) $this->UpdateFormField($name, 'enabled', $UserID !== ''); } private function passwordHash(string $password): string { if (strlen($password) < 8 || strlen($password) > 72 || str_contains($password, "\0")) throw new InvalidArgumentException('Das Passwort muss 8–72 Bytes lang sein.'); return password_hash($password, defined('PASSWORD_ARGON2ID') ? PASSWORD_ARGON2ID : PASSWORD_DEFAULT); } private function parseGrants(string $json, bool $objects = false): array { $rows = json_decode($json, true); if (!is_array($rows) || !array_is_list($rows) || count($rows) > 256) throw new InvalidArgumentException('Ungültige Freigabeliste.'); $result = []; foreach ($rows as $row) { if (!is_array($row)) throw new InvalidArgumentException('Ungültige Freigabe.'); $target = $objects ? (int) ($row['target'] ?? 0) : (string) ($row['target'] ?? ''); if ($target === '' || $target === 0) continue; if (!in_array($row['access'] ?? '', ['view', 'control'], true)) throw new InvalidArgumentException('Bitte für jede Freigabe ein Recht auswählen.'); if ($objects && (!IPS_ObjectExists($target) || !in_array((int) IPS_GetObject($target)['ObjectType'], [0, 1, 2, 4, 6], true))) throw new InvalidArgumentException('Das freigegebene Objekt existiert nicht oder ist kein Gerät, Datenpunkt, Ereignis oder Bereich.'); $key = (string) $target; $level = $row['access'] === 'control' || ($result[$key]['access'] ?? '') === 'control' ? 'control' : 'view'; $result[$key] = ['target' => $target, 'access' => $level]; } return array_values($result); } public function SaveAccessUser(string $UserID, string $Name, string $Role, bool $Enabled, bool $ViewAll, bool $ControlAll, string $Rooms, string $Devices, string $Objects, string $Password): string { try { $Name = trim($Name); if (preg_match('/^[\p{L}\p{N}][\p{L}\p{N}_.@ -]{1,63}$/uD', $Name) !== 1) throw new InvalidArgumentException('Benutzername: 2–64 Buchstaben, Zahlen, Leerzeichen oder . _ @ -'); if (!in_array($Role, ['admin', 'user'], true)) throw new InvalidArgumentException('Ungültige Rolle.'); $rooms = $this->parseGrants($Rooms); $devices = $this->parseGrants($Devices); $objects = $this->parseGrants($Objects, true); $hash = $Password === '' ? null : $this->passwordHash($Password); $id = $this->accessLock(function () use ($UserID, $Name, $Role, $Enabled, $ViewAll, $ControlAll, $rooms, $devices, $objects, $hash): string { $accounts = $this->accounts(); if ($UserID !== '' && !isset($accounts[$UserID])) throw new InvalidArgumentException('Benutzer nicht gefunden.'); foreach ($accounts as $id => $a) if ($id !== $UserID && mb_strtolower($a['name']) === mb_strtolower($Name)) throw new InvalidArgumentException('Dieser Benutzername ist bereits vergeben.'); if ($UserID === '' && count($accounts) >= 128) throw new InvalidArgumentException('Maximal 128 Benutzer pro Instanz.'); if ($UserID === '' && $hash === null) throw new InvalidArgumentException('Für neue Benutzer bitte ein Passwort setzen.'); $id = $UserID ?: bin2hex(random_bytes(16)); $accounts[$id] = ['name' => $Name, 'role' => $Role, 'enabled' => $Enabled, 'view_all' => $ViewAll || $ControlAll, 'control_all' => $ControlAll, 'rooms' => $rooms, 'devices' => $devices, 'objects' => $objects, 'password' => $hash ?? $accounts[$id]['password'], 'epoch' => $this->newToken()]; $this->writeJsonAttribute('Accounts', $accounts); $this->clearUserSessions($id); return $id; }); $this->SelectAccessUser($id); return 'Benutzer gespeichert. Vorherige Anmeldungen dieses Benutzers wurden beendet.'; } catch (InvalidArgumentException $e) { return $e->getMessage(); } } private function clearUserSessions(string $id): void { $this->writeJsonAttribute('Sessions', array_filter($this->jsonAttribute('Sessions', []), static fn(array $s): bool => $s['account'] !== $id)); } public function ResetUserPassword(string $UserID, string $Password): string { try { $hash = $this->passwordHash($Password); $this->accessLock(function () use ($UserID, $hash): void { $accounts = $this->accounts(); if (!isset($accounts[$UserID])) throw new InvalidArgumentException('Bitte einen bestehenden Benutzer auswählen.'); $accounts[$UserID]['password'] = $hash; $accounts[$UserID]['epoch'] = $this->newToken(); $this->writeJsonAttribute('Accounts', $accounts); $this->clearUserSessions($UserID); $limits = $this->jsonAttribute('LoginThrottle', []); unset($limits['name:' . hash('sha256', mb_strtolower($accounts[$UserID]['name']))]); $this->writeJsonAttribute('LoginThrottle', $limits); }); $this->UpdateFormField('AccountPassword', 'value', ''); return 'Passwort zurückgesetzt. Bestehende Anmeldungen dieses Benutzers sind beendet.'; } catch (InvalidArgumentException $e) { return $e->getMessage(); } } public function RevokeUserSessions(string $UserID): string { $this->accessLock(fn() => $this->clearUserSessions($UserID)); return 'Bestehende Anmeldungen dieses Benutzers wurden beendet.'; } public function DeleteAccessUser(string $UserID): string { $this->accessLock(function () use ($UserID): void { $accounts = $this->accounts(); unset($accounts[$UserID]); $this->writeJsonAttribute('Accounts', $accounts); $this->clearUserSessions($UserID); }); $this->SelectAccessUser(''); return 'Benutzer gelöscht.'; } }