added usermanagement
This commit is contained in:
1 parent
3acce4eaf8
commit
088d763ff6
17 files changed
+1850
-785
No files matched your search
@@ -0,0 +1,200 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
/** Instance-local accounts and revocable HttpOnly sessions. Console actions are never exposed through the WebHook API. */
|
||||
trait NextFloorAccess
|
||||
{
|
||||
private ?array $requestUser = null;
|
||||
private ?array $requestScope = null;
|
||||
private const SESSION_TTL = 43200;
|
||||
private const SESSION_IDLE = 7200;
|
||||
|
||||
private function accessLock(callable $operation): mixed
|
||||
{
|
||||
$name = 'NextFloorAccess_' . $this->InstanceID;
|
||||
$native = function_exists('IPS_SemaphoreEnter');
|
||||
if ($native && !IPS_SemaphoreEnter($name, 3000)) throw new RuntimeException('access_busy');
|
||||
try { return $operation(); }
|
||||
finally { if ($native) IPS_SemaphoreLeave($name); }
|
||||
}
|
||||
|
||||
private function accounts(): array { return $this->jsonAttribute('Accounts', []); }
|
||||
|
||||
/** A short-lived, single-use console ticket; no reusable admin credential in browser URLs. */
|
||||
private function consoleUrl(): string
|
||||
{
|
||||
$ticket = $this->newToken();
|
||||
$this->accessLock(function () use ($ticket): void {
|
||||
$tickets = array_filter($this->jsonAttribute('ConsoleTickets', []), static fn(array $t): bool => $t['expires'] > time());
|
||||
$tickets = array_slice($tickets, -19, null, true);
|
||||
$tickets[hash('sha256', $ticket)] = ['expires' => time() + 90, 'epoch' => $this->ensureAccessToken()];
|
||||
$this->writeJsonAttribute('ConsoleTickets', $tickets);
|
||||
});
|
||||
return '/hook/' . $this->hookPath() . '/designer?mode=designer&ticket=' . rawurlencode($ticket);
|
||||
}
|
||||
|
||||
private function sessionCookie(): string { return 'NFSC_Session_' . $this->InstanceID; }
|
||||
private function loginCookie(): string { return 'NFSC_Login_' . $this->InstanceID; }
|
||||
|
||||
private function accessCookie(string $name, string $value, int $expires = 0): void
|
||||
{
|
||||
setcookie($name, $value, ['expires' => $expires, 'path' => '/hook/' . $this->hookPath() . '/',
|
||||
'secure' => $this->secureRequest(), 'httponly' => true, 'samesite' => 'Strict']);
|
||||
}
|
||||
|
||||
private function secureRequest(): bool
|
||||
{
|
||||
// A proxy header can only strengthen cookie protection, never turn native HTTPS off.
|
||||
return (($_SERVER['HTTPS'] ?? '') !== '' && ($_SERVER['HTTPS'] ?? '') !== 'off') || ($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? '') === 'https';
|
||||
}
|
||||
|
||||
private function createSession(string $accountID, array $account, bool $remember = false): array
|
||||
{
|
||||
$token = $this->newToken();
|
||||
$id = hash('sha256', $token);
|
||||
$session = ['account' => $accountID, 'epoch' => $account['epoch'], 'csrf' => $this->newToken(),
|
||||
'expires' => time() + ($remember ? 2592000 : self::SESSION_TTL), 'idle' => $remember ? 604800 : self::SESSION_IDLE, 'seen' => time()];
|
||||
// Called inside accessLock, including ticket exchange and password login.
|
||||
$sessions = array_filter($this->jsonAttribute('Sessions', []), static fn(array $s): bool => $s['expires'] > time() && $s['seen'] > time() - ($s['idle'] ?? self::SESSION_IDLE));
|
||||
if (count($sessions) >= 128) throw new RuntimeException('session_limit');
|
||||
$sessions[$id] = $session;
|
||||
$this->writeJsonAttribute('Sessions', $sessions);
|
||||
$this->accessCookie($this->sessionCookie(), $token, $remember ? $session['expires'] : 0);
|
||||
return [...$account, 'id' => $accountID, 'session_id' => $id, 'csrf' => $session['csrf']];
|
||||
}
|
||||
|
||||
private function resolveSession(): ?array
|
||||
{
|
||||
$token = $_COOKIE[$this->sessionCookie()] ?? '';
|
||||
if (!is_string($token) || preg_match('/^[a-f0-9]{64}$/D', $token) !== 1) return null;
|
||||
return $this->accessLock(function () use ($token): ?array {
|
||||
$id = hash('sha256', $token);
|
||||
$sessions = $this->jsonAttribute('Sessions', []);
|
||||
$s = $sessions[$id] ?? null;
|
||||
if (!$s || $s['expires'] <= time() || $s['seen'] <= time() - ($s['idle'] ?? self::SESSION_IDLE)) return null;
|
||||
$account = $s['account'] === '__console__' ? ['name' => 'Symcon-Konsole', 'role' => 'admin', 'enabled' => true, 'epoch' => $this->ensureAccessToken()]
|
||||
: ($this->accounts()[$s['account']] ?? null);
|
||||
if (!$account || !$account['enabled'] || !hash_equals((string) $account['epoch'], (string) $s['epoch'])) return null;
|
||||
if ($s['seen'] < time() - 60) {
|
||||
$sessions[$id]['seen'] = time();
|
||||
$this->writeJsonAttribute('Sessions', $sessions);
|
||||
}
|
||||
return [...$account, 'id' => $s['account'], 'session_id' => $id, 'csrf' => $s['csrf']];
|
||||
});
|
||||
}
|
||||
|
||||
private function exchangeConsoleTicket(string $ticket): bool
|
||||
{
|
||||
if (preg_match('/^[a-f0-9]{64}$/D', $ticket) !== 1) return false;
|
||||
return $this->accessLock(function () use ($ticket): bool {
|
||||
$tickets = $this->jsonAttribute('ConsoleTickets', []);
|
||||
$key = hash('sha256', $ticket);
|
||||
$grant = $tickets[$key] ?? null;
|
||||
unset($tickets[$key]);
|
||||
$this->writeJsonAttribute('ConsoleTickets', $tickets);
|
||||
if (!$grant || $grant['expires'] <= time() || !hash_equals($this->ensureAccessToken(), $grant['epoch'])) return false;
|
||||
$this->requestUser = $this->createSession('__console__', ['name' => 'Symcon-Konsole', 'role' => 'admin', 'enabled' => true, 'epoch' => $grant['epoch']]);
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
private function safeMode(): string { return ($_GET['mode'] ?? '') === 'tile' ? 'tile' : 'designer'; }
|
||||
private function entryUrl(string $tail = 'designer'): string { return '/hook/' . $this->hookPath() . '/' . $tail . '?mode=' . $this->safeMode(); }
|
||||
private function accessRedirect(string $url): void { header('Location: ' . $url, true, 303); header('Cache-Control: no-store'); }
|
||||
|
||||
private function validOrigin(): bool
|
||||
{
|
||||
$origin = $_SERVER['HTTP_ORIGIN'] ?? '';
|
||||
if ($origin === '') return true; // non-browser clients still require the CSRF value and session cookie
|
||||
$parts = parse_url($origin);
|
||||
if (!is_array($parts) || ($parts['scheme'] ?? '') !== ($this->secureRequest() ? 'https' : 'http')) return false;
|
||||
$authority = strtolower((string) ($parts['host'] ?? '') . (isset($parts['port']) ? ':' . $parts['port'] : ''));
|
||||
return $authority !== '' && hash_equals(strtolower((string) ($_SERVER['HTTP_HOST'] ?? '')), $authority);
|
||||
}
|
||||
|
||||
private function validCsrf(): bool
|
||||
{
|
||||
$value = $_SERVER['HTTP_X_NEXTFLOOR_CSRF'] ?? $_POST['csrf'] ?? '';
|
||||
return $this->requestUser !== null && is_string($value) && $value !== '' && $this->validOrigin()
|
||||
&& hash_equals($this->requestUser['csrf'], $value);
|
||||
}
|
||||
|
||||
/** Login stays a regular HTML form, including with JavaScript disabled and on small touch screens. */
|
||||
private function loginPage(string $error = '', int $status = 200): void
|
||||
{
|
||||
$csrf = $this->newToken();
|
||||
$this->accessCookie($this->loginCookie(), $csrf);
|
||||
$escape = static fn(string $s): string => htmlspecialchars($s, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
|
||||
http_response_code($status);
|
||||
header('Content-Type: text/html; charset=utf-8');
|
||||
header('Cache-Control: no-store');
|
||||
$configured = count(array_filter($this->accounts(), static fn(array $a): bool => $a['enabled'])) > 0;
|
||||
echo '<!doctype html><html lang="de"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">'
|
||||
. '<title>Anmelden · ' . $escape($this->viewTitle()) . '</title><style>html{color-scheme:dark}body{margin:0;min-height:100dvh;display:grid;place-items:center;background:#0c1320;color:#e6edf5;font:16px/1.5 system-ui}main{box-sizing:border-box;width:min(420px,calc(100% - 32px));padding:32px;background:#1b2432;border:1px solid #344255;border-radius:18px;box-shadow:0 16px 60px #0005}h1{margin:0 0 4px;font-size:25px}p{color:#aebdce}label{display:block;margin:18px 0 6px}input,button{box-sizing:border-box;width:100%;padding:12px 14px;border-radius:9px;border:1px solid #465872;font:inherit}input{background:#101a28;color:inherit}button{margin-top:24px;background:#1bb8e8;color:#061624;font-weight:700;cursor:pointer}input:focus,button:focus{outline:2px solid #45d0ff;outline-offset:3px}[role=alert]{padding:10px;background:#82353555;border-radius:8px;color:#ffc4c4}.note{font-size:13px}</style></head><body><main><h1>'
|
||||
. $escape($this->viewTitle()) . '</h1><p>Mit deinem NextFloor-Konto anmelden.</p>'
|
||||
. ($error !== '' ? '<p role="alert">' . $escape($error) . '</p>' : '')
|
||||
. ($configured ? '<form method="post" action="' . $escape($this->entryUrl('login')) . '"><input type="hidden" name="csrf" value="' . $csrf . '">'
|
||||
. '<label for="username">Benutzername</label><input id="username" name="username" autocomplete="username" required maxlength="64" autofocus>'
|
||||
. '<label for="password">Passwort</label><input id="password" name="password" type="password" autocomplete="current-password" required maxlength="72">'
|
||||
. '<label style="display:flex;gap:9px;align-items:center;font-size:14px"><input style="width:auto" type="checkbox" name="remember" value="1">Angemeldet bleiben (30 Tage)</label><button type="submit">Anmelden</button></form><p class="note">Passwort vergessen? Der Symcon-Administrator kann es in der NextFloor-Instanz zurücksetzen.</p>'
|
||||
: '<p role="status">Noch kein Benutzer eingerichtet. Lege in der Symcon-Konfiguration der NextFloor-Instanz zuerst einen Benutzer mit Passwort an.</p>')
|
||||
. '</main></body></html>';
|
||||
}
|
||||
|
||||
private function passwordLogin(): void
|
||||
{
|
||||
$csrf = $_POST['csrf'] ?? '';
|
||||
$nonce = $_COOKIE[$this->loginCookie()] ?? '';
|
||||
if (!$this->validOrigin() || !is_string($csrf) || !is_string($nonce) || strlen($nonce) !== 64 || !hash_equals($nonce, $csrf)) {
|
||||
$this->loginPage('Die Anmeldung ist abgelaufen. Bitte erneut versuchen.', 403);
|
||||
return;
|
||||
}
|
||||
$name = is_string($_POST['username'] ?? null) ? mb_strtolower(trim($_POST['username'])) : '';
|
||||
$password = is_string($_POST['password'] ?? null) ? $_POST['password'] : '';
|
||||
$result = $this->accessLock(function () use ($name, $password): string {
|
||||
$now = time();
|
||||
$limits = array_filter($this->jsonAttribute('LoginThrottle', []), static fn(array $v): bool => $v['until'] > time());
|
||||
$ipKey = 'ip:' . hash('sha256', (string) ($_SERVER['REMOTE_ADDR'] ?? 'unknown'));
|
||||
$nameKey = 'name:' . hash('sha256', $name);
|
||||
if (($limits[$ipKey]['count'] ?? 0) >= 40 || ($limits[$nameKey]['count'] ?? 0) >= 8) return 'limited';
|
||||
$found = null;
|
||||
foreach ($this->accounts() as $id => $a) if (mb_strtolower($a['name']) === $name) { $found = [$id, $a]; break; }
|
||||
// Use the same platform algorithm/cost for an unknown username as for real accounts.
|
||||
$hash = $found[1]['password'] ?? $this->ReadAttributeString('LoginDummyHash');
|
||||
$valid = strlen($password) <= 72 && !str_contains($password, "\0") && password_verify($password, $hash);
|
||||
if (!$valid || !$found || !$found[1]['enabled']) {
|
||||
foreach ([$ipKey, $nameKey] as $key) $limits[$key] = ['count' => ($limits[$key]['count'] ?? 0) + 1, 'until' => $limits[$key]['until'] ?? $now + 900];
|
||||
$this->writeJsonAttribute('LoginThrottle', array_slice($limits, -1024, null, true));
|
||||
return 'invalid';
|
||||
}
|
||||
unset($limits[$nameKey]);
|
||||
$this->writeJsonAttribute('LoginThrottle', $limits);
|
||||
$this->requestUser = $this->createSession($found[0], $found[1], ($_POST['remember'] ?? '') === '1');
|
||||
return 'ok';
|
||||
});
|
||||
if ($result !== 'ok') { $this->loginPage($result === 'limited' ? 'Zu viele Anmeldeversuche. Bitte in 15 Minuten erneut versuchen.' : 'Benutzername oder Passwort ist ungültig.', $result === 'limited' ? 429 : 401); return; }
|
||||
$this->accessCookie($this->loginCookie(), '', time() - 3600);
|
||||
$this->accessRedirect($this->entryUrl());
|
||||
}
|
||||
|
||||
private function logoutSession(): void
|
||||
{
|
||||
$id = $this->requestUser['session_id'] ?? '';
|
||||
$this->accessLock(function () use ($id): void {
|
||||
$sessions = $this->jsonAttribute('Sessions', []); unset($sessions[$id]); $this->writeJsonAttribute('Sessions', $sessions);
|
||||
});
|
||||
$this->accessCookie($this->sessionCookie(), '', time() - 3600);
|
||||
$this->requestUser = null;
|
||||
$this->accessRedirect($this->entryUrl('login'));
|
||||
}
|
||||
|
||||
private function publicAccess(): array
|
||||
{
|
||||
$admin = $this->requestUser['role'] === 'admin';
|
||||
$canControl = $admin || ($this->requestUser['control_all'] ?? false);
|
||||
foreach (['rooms', 'devices', 'objects'] as $group) foreach ($this->requestUser[$group] ?? [] as $g) if (($g['access'] ?? '') === 'control') $canControl = true;
|
||||
return ['id' => $this->requestUser['id'], 'name' => $this->requestUser['name'], 'is_admin' => $admin,
|
||||
'view_all' => $admin || ($this->requestUser['view_all'] ?? false), 'control_all' => $admin || ($this->requestUser['control_all'] ?? false), 'can_control' => $canControl];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,286 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
class NextFloorDenied extends RuntimeException {}
|
||||
|
||||
/** Deny by default; project geometry and live data are separate capabilities. */
|
||||
trait NextFloorPermissions
|
||||
{
|
||||
private const REF_FIELDS = ['entity', 'entity_id', 'device', 'tracker', 'power', 'energy', 'temperature', 'humidity', 'co2', 'illuminance',
|
||||
'supply_vsr', 'extract_vsr', 'supply_temperature', 'extract_temperature', 'reheat', 'status', 'schedules',
|
||||
'floor_heating', 'clean_entity', 'panel', 'hidden', 'no_state', 'cover', 'cover2', 'cover_tilt', 'cover2_tilt',
|
||||
'contact', 'contact2', 'tilt', 'tilt2', 'position', 'tilt_angle', 'lock', 'door_left', 'door_right', 'soc', 'charge', 'export',
|
||||
'gang_entities', 'flow', 'return', 'command', 'feedback', 'circulation_temperature', 'hot_water', 'cold_water',
|
||||
'start', 'end', 'duration', 'start_time', 'end_time', 'charging_time', 'charged_energy', 'lock_status', 'range', 'charging', 'plugged', 'departure',
|
||||
'grid', 'solar', 'battery', 'battery_soc', 'consumption', 'tariff', 'meter', 'favorites', 'condition', 'pressure', 'wind_speed', 'wind_gust_speed', 'wind_bearing',
|
||||
'cloud_coverage', 'precipitation', 'precipitation_total', 'uv_index', 'visibility', 'snow', 'fog', 'lightning'];
|
||||
private const REF_GROUPS = ['climate', 'hvac', 'utility_meters', 'electricity', 'water', 'gas', 'heating', 'cooling',
|
||||
'values', 'charging', 'hydronic', 'circuits', 'sensors', 'stations', 'pump', 'valve', 'circulation', 'show_when', 'car', 'gates', 'settings', 'presence', 'weather_variables'];
|
||||
|
||||
private function refKey(string $key): bool { return in_array($key, self::REF_FIELDS, true) || preg_match('/_(?:entit(?:y\d*|ies)|sensor\d*)$/D', $key) === 1; }
|
||||
private function entityRefs(array $node): array
|
||||
{
|
||||
$ids = [];
|
||||
foreach ($node as $key => $value) {
|
||||
if (!is_int($key) && !$this->refKey($key) && !in_array($key, self::REF_GROUPS, true)) continue;
|
||||
if (is_string($value) && $this->variableIdForEntity($value) !== null) $ids[] = $this->variableIdForEntity($value);
|
||||
if (is_array($value)) $ids = [...$ids, ...$this->entityRefs($value)];
|
||||
}
|
||||
return array_values(array_unique($ids));
|
||||
}
|
||||
|
||||
private function planKey(string $kind, array $floor, string $id): string { return $kind . ':' . rawurlencode((string) $floor['id']) . ':' . rawurlencode($id); }
|
||||
|
||||
private function accessCatalog(): array
|
||||
{
|
||||
$rooms = []; $devices = [];
|
||||
foreach ($this->building()['floors'] ?? [] as $floor) {
|
||||
$prefix = (string) ($floor['name'] ?? 'Etage') . ' / ';
|
||||
foreach ($floor['rooms'] ?? [] as $room) $rooms[] = ['caption' => $prefix . ($room['name'] ?? $room['id']), 'value' => $this->planKey('room', $floor, (string) $room['id'])];
|
||||
foreach (['furniture', 'openings', 'placements'] as $group) foreach ($floor[$group] ?? [] as $item) {
|
||||
$id = (string) ($item['id'] ?? $item['entity_id'] ?? '');
|
||||
if ($id === '') continue;
|
||||
$room = $this->itemRoom($floor, $item);
|
||||
$label = trim((string) ($item['name'] ?? ''));
|
||||
if ($label === '' && ($native = $this->variableIdForEntity($id)) !== null && IPS_ObjectExists($native)) {
|
||||
$parts = []; $at = $native; $seen = [];
|
||||
while ($at > 0 && IPS_ObjectExists($at) && count($parts) < 3 && !isset($seen[$at])) {
|
||||
$seen[$at] = true; array_unshift($parts, IPS_GetName($at)); $at = (int) IPS_GetObject($at)['ParentID'];
|
||||
}
|
||||
$label = implode(' / ', $parts);
|
||||
}
|
||||
if ($label === '') $label = str_replace('_', ' ', (string) ($item['type'] ?? 'Gerät'));
|
||||
$devices[] = ['caption' => $prefix . ($room ? ($room['name'] ?? '') . ' / ' : '') . $label, 'value' => $this->planKey($group, $floor, $id)];
|
||||
}
|
||||
}
|
||||
return ['rooms' => $rooms, 'devices' => $devices];
|
||||
}
|
||||
|
||||
private function insideRoom(float $x, float $z, array $points): bool
|
||||
{
|
||||
$inside = false; $count = count($points);
|
||||
for ($i = 0, $j = $count - 1; $i < $count; $j = $i++) {
|
||||
[$xi, $zi] = $points[$i]; [$xj, $zj] = $points[$j];
|
||||
if (($zi > $z) !== ($zj > $z) && $x < ($xj - $xi) * ($z - $zi) / ($zj - $zi) + $xi) $inside = !$inside;
|
||||
}
|
||||
return $inside;
|
||||
}
|
||||
|
||||
private function itemRoom(array $floor, array $item): ?array
|
||||
{
|
||||
foreach ($floor['rooms'] ?? [] as $room) {
|
||||
if (isset($item['room_id']) ? $item['room_id'] === $room['id'] : (isset($item['x'], $item['z']) && $this->insideRoom((float) $item['x'], (float) $item['z'], $room['points'] ?? []))) return $room;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private function grantMap(array $grants): array
|
||||
{
|
||||
$map = [];
|
||||
foreach ($grants as $g) if (in_array($g['access'] ?? '', ['view', 'control'], true)) $map[(string) $g['target']] = $g['access'];
|
||||
return $map;
|
||||
}
|
||||
|
||||
private function isAdministrator(): bool { return ($this->requestUser['role'] ?? '') === 'admin'; }
|
||||
|
||||
private function scope(?array $tree = null): array
|
||||
{
|
||||
if ($this->requestScope !== null) return $this->requestScope;
|
||||
if ($this->requestUser === null) throw new NextFloorDenied('authentication_required');
|
||||
$user = $this->requestUser;
|
||||
$all = $this->isAdministrator();
|
||||
$scope = ['view_all' => $all || ($user['view_all'] ?? false) || ($user['control_all'] ?? false), 'control_all' => $all || ($user['control_all'] ?? false),
|
||||
'read' => [], 'write' => [], 'native_read' => [], 'entities' => [], 'rooms' => $this->grantMap($user['rooms'] ?? []), 'devices' => $this->grantMap($user['devices'] ?? [])];
|
||||
if ($all) return $this->requestScope = $scope;
|
||||
$tree ??= $this->objectTree();
|
||||
$parents = []; $native = [];
|
||||
foreach ($tree['objects'] as $o) $parents[(int) $o['object_id']] = (int) $o['parent_id'];
|
||||
foreach ($tree['variables'] as $v) {
|
||||
$native[(int) $v['attributes']['symcon_id']] = true;
|
||||
$scope['entities'][(int) $v['attributes']['symcon_id']] = $v['entity_id'];
|
||||
}
|
||||
$descendantCache = [];
|
||||
$descendants = static function (int $root) use ($native, $parents, &$descendantCache): array {
|
||||
if (isset($descendantCache[$root])) return $descendantCache[$root];
|
||||
$ids = [];
|
||||
foreach ($native as $id => $_) {
|
||||
$at = $id; $seen = [];
|
||||
while ($at > 0 && !isset($seen[$at])) {
|
||||
if ($at === $root) { $ids[] = $id; break; }
|
||||
$seen[$at] = true; $at = $parents[$at] ?? 0;
|
||||
}
|
||||
}
|
||||
return $descendantCache[$root] = $ids;
|
||||
};
|
||||
$allow = static function (array $ids, string $level, bool $explicit = false) use (&$scope, $native): void {
|
||||
foreach ($ids as $id) if (isset($native[$id])) {
|
||||
$scope['read'][$id] = true;
|
||||
if ($level === 'control') $scope['write'][$id] = true;
|
||||
if ($explicit) $scope['native_read'][$id] = true;
|
||||
}
|
||||
};
|
||||
foreach ($user['objects'] ?? [] as $g) {
|
||||
$target = (int) $g['target']; $seen = [];
|
||||
while (IPS_ObjectExists($target) && (int) IPS_GetObject($target)['ObjectType'] === 6 && !isset($seen[$target])) {
|
||||
$seen[$target] = true; $target = (int) IPS_GetLink($target)['TargetID'];
|
||||
}
|
||||
$allow($descendants($target), $g['access'], true);
|
||||
}
|
||||
foreach ($this->building()['floors'] ?? [] as $floor) {
|
||||
foreach ($floor['rooms'] ?? [] as $room) {
|
||||
$key = $this->planKey('room', $floor, (string) $room['id']);
|
||||
$own = $scope['rooms'][$key] ?? null;
|
||||
$level = $scope['control_all'] || $own === 'control' ? 'control' : ($scope['view_all'] ? 'view' : $own);
|
||||
if ($level === null) continue;
|
||||
$scope['rooms'][$key] = $level;
|
||||
$allow($this->entityRefs($room), $level);
|
||||
foreach ([$room['area_id'] ?? '', ...($room['sub_areas'] ?? [])] as $area) if (preg_match('/^symcon-category-(\d+)$/D', (string) $area, $m) === 1) $allow($descendants((int) $m[1]), $level);
|
||||
}
|
||||
foreach (['furniture', 'openings', 'placements'] as $group) foreach ($floor[$group] ?? [] as $item) {
|
||||
$id = (string) ($item['id'] ?? $item['entity_id'] ?? '');
|
||||
$own = $scope['devices'][$this->planKey($group, $floor, $id)] ?? null;
|
||||
$room = $this->itemRoom($floor, $item);
|
||||
$inherited = $room ? ($scope['rooms'][$this->planKey('room', $floor, (string) $room['id'])] ?? null) : null;
|
||||
$level = $scope['control_all'] || $own === 'control' || $inherited === 'control' ? 'control' : ($own ?? $inherited ?? ($scope['view_all'] ? 'view' : null));
|
||||
if ($level !== null) { $scope['devices'][$this->planKey($group, $floor, $id)] = $level; $allow($this->entityRefs($item), $level); }
|
||||
}
|
||||
if ($scope['view_all']) {
|
||||
$allow($this->entityRefs($floor), $scope['control_all'] ? 'control' : 'view');
|
||||
foreach ($floor['outdoor'] ?? [] as $area) $allow($this->entityRefs($area), $scope['control_all'] ? 'control' : 'view');
|
||||
}
|
||||
}
|
||||
if ($scope['view_all']) $allow($this->entityRefs($this->building()), $scope['control_all'] ? 'control' : 'view');
|
||||
return $this->requestScope = $scope;
|
||||
}
|
||||
|
||||
private function allowedEntity(string $entity, bool $write): bool
|
||||
{
|
||||
$id = $this->variableIdForEntity($entity);
|
||||
if ($id === null) return false;
|
||||
$s = $this->scope();
|
||||
return $this->isAdministrator() || ($write ? isset($s['write'][$id]) : isset($s['read'][$id]));
|
||||
}
|
||||
|
||||
/** Authorize every target before the first write: mixed bulk commands cannot partially execute. */
|
||||
private function authorizeApi(string $action, array $request): void
|
||||
{
|
||||
if ($this->requestUser === null) throw new NextFloorDenied('authentication_required');
|
||||
$read = ['bootstrap', 'variables/snapshot', 'archive/trend', 'building/get', 'image/get', 'packs/list', 'transport/read', 'transport/release'];
|
||||
if (!$this->isAdministrator() && !in_array($action, [...$read, 'variables/action'], true)) throw new NextFloorDenied('admin_required');
|
||||
if ($action === 'archive/trend' && (!is_string($request['entity_id'] ?? null) || !$this->allowedEntity($request['entity_id'], false))) throw new NextFloorDenied('read_forbidden');
|
||||
if ($action === 'variables/action') {
|
||||
$targets = $request['data']['entity_id'] ?? [];
|
||||
$targets = is_array($targets) ? $targets : [$targets];
|
||||
if (!$targets || count($targets) > 256) throw new NextFloorDenied('invalid_targets');
|
||||
foreach ($targets as $target) {
|
||||
if (!is_string($target) || !$this->allowedEntity($target, true)) throw new NextFloorDenied('control_forbidden');
|
||||
$id = $this->variableIdForEntity($target);
|
||||
if (!$this->isAdministrator() && IPS_VariableExists($id)) {
|
||||
$v = IPS_GetVariable($id); $actionID = (int) ($v['VariableCustomAction'] ?: $v['VariableAction']);
|
||||
if ($actionID <= 0) throw new NextFloorDenied('variable_readonly');
|
||||
}
|
||||
}
|
||||
}
|
||||
if ($action === 'image/get' && !$this->isAdministrator()) {
|
||||
$id = is_string($request['image_id'] ?? null) ? $request['image_id'] : '';
|
||||
$images = [];
|
||||
$visible = $this->visibleBuilding();
|
||||
array_walk_recursive($visible, static function (mixed $value, mixed $key) use (&$images): void {
|
||||
if (!is_string($value)) return;
|
||||
if ($key === 'image_id') $images[] = $value;
|
||||
elseif (is_string($key) && preg_match('/^(?:picture|image|url|.*_image)$/D', $key) && str_starts_with($value, 'image:')) $images[] = substr($value, 6);
|
||||
});
|
||||
if ($id === '' || !in_array($id, $images, true)) throw new NextFloorDenied('image_forbidden');
|
||||
}
|
||||
}
|
||||
|
||||
private function visibleTree(array $tree): array
|
||||
{
|
||||
if ($this->isAdministrator()) return $tree;
|
||||
$scope = $this->scope($tree);
|
||||
$variables = [];
|
||||
foreach ($tree['variables'] as $v) {
|
||||
$id = (int) $v['attributes']['symcon_id'];
|
||||
if (!isset($scope['read'][$id])) continue;
|
||||
$can = isset($scope['write'][$id]) && (($v['attributes']['symcon_schedule'] ?? false) || ($v['attributes']['symcon_has_action'] ?? false));
|
||||
$v['attributes']['symcon_can_control'] = $can;
|
||||
if (!$can) $v['attributes']['symcon_has_action'] = false;
|
||||
$variables[] = $v;
|
||||
}
|
||||
$areaIDs = array_fill_keys(array_filter(array_column($variables, 'area_id'), 'is_string'), true);
|
||||
$areas = array_filter($tree['areas'], static fn(array $a): bool => isset($areaIDs[$a['area_id']]));
|
||||
// Utility discovery also needs topology (e.g. Büro / Strom / Leistung). Keep only permitted
|
||||
// variable nodes and their ancestors; never expose unrelated branches or variable values.
|
||||
$nodes = [];
|
||||
foreach ($tree['objects'] as $node) $nodes[(int) $node['object_id']] = $node;
|
||||
$keep = [];
|
||||
foreach ($variables as $v) {
|
||||
$at = (int) $v['attributes']['symcon_id'];
|
||||
while ($at > 0 && isset($nodes[$at]) && !isset($keep[$at])) {
|
||||
$keep[$at] = true; $at = (int) $nodes[$at]['parent_id'];
|
||||
}
|
||||
}
|
||||
$objects = array_values(array_filter($tree['objects'], static fn(array $node): bool => isset($keep[(int) $node['object_id']])));
|
||||
return ['variables' => $variables, 'areas' => array_values($areas), 'objects' => $objects];
|
||||
}
|
||||
|
||||
private function maskRefs(array $node, array $allow): array
|
||||
{
|
||||
foreach ($node as $key => $v) {
|
||||
// Strip unknown/legacy binding fields too. Geometry identifiers and captions are not live bindings.
|
||||
if (in_array($key, ['id', 'name', 'type', 'label', 'icon', 'room_id', 'area_id', 'parent_meter', 'buffer_id'], true)) continue;
|
||||
if (is_string($v) && ($id = $this->variableIdForEntity($v)) !== null && !isset($allow[$id])) $node[$key] = 'none';
|
||||
elseif (is_array($v)) $node[$key] = $this->maskRefs($v, $allow);
|
||||
}
|
||||
return $node;
|
||||
}
|
||||
|
||||
private function visibleBuilding(): array
|
||||
{
|
||||
$building = $this->building();
|
||||
if ($this->isAdministrator()) return $building;
|
||||
$s = $this->scope();
|
||||
// Admin-owned executable UI configuration is never part of a user view.
|
||||
$building['settings']['plugins'] = []; $building['settings']['buttons'] = [];
|
||||
foreach (['custom_buttons', 'media_presets', 'announce_phrases'] as $key) unset($building['settings'][$key]);
|
||||
foreach ($building['floors'] as &$floor) {
|
||||
$panels = [];
|
||||
foreach (['furniture', 'openings', 'placements'] as $group) foreach ($floor[$group] ?? [] as $i => $item) {
|
||||
$id = (string) ($item['id'] ?? $item['entity_id'] ?? '');
|
||||
$granted = $s['view_all'] || isset($s['devices'][$this->planKey($group, $floor, $id)]);
|
||||
$filtered = $granted ? $item : $this->maskRefs($item, $s['native_read']);
|
||||
unset($filtered['tap']);
|
||||
if (!$granted) {
|
||||
unset($filtered['show_when'], $filtered['pictures'], $filtered['screen_pictures'], $filtered['picture']);
|
||||
if (empty($item['entity'])) $filtered['entity'] = 'none';
|
||||
if (!$this->entityRefs($filtered)) { $filtered['power_card'] = false; $filtered['hydronic']['card'] = false; }
|
||||
}
|
||||
$floor[$group][$i] = $filtered;
|
||||
$room = $this->itemRoom($floor, $item);
|
||||
if ($room) foreach ($this->entityRefs($filtered) as $native) $panels[$room['id']][$native] = true;
|
||||
}
|
||||
foreach ($floor['rooms'] as &$room) {
|
||||
$key = $this->planKey('room', $floor, (string) $room['id']);
|
||||
if ($s['view_all'] || isset($s['rooms'][$key])) continue;
|
||||
$room = $this->maskRefs($room, []);
|
||||
$room['area_id'] = null; $room['sub_areas'] = []; $room['climate_card'] = false;
|
||||
$room['symcon_read_room'] = false;
|
||||
$room['climate'] = ['temperature' => 'none', 'humidity' => 'none', 'co2' => 'none', 'illuminance' => 'none'];
|
||||
$room['hvac'] = null; $room['utility_meters'] = null; $room['moods'] = []; $room['floor_heating'] = 'none';
|
||||
$room['panel'] = array_values(array_filter(array_map(static fn(int $id): ?string => $s['entities'][$id] ?? null, array_keys($panels[$room['id']] ?? []))));
|
||||
}
|
||||
unset($room);
|
||||
if (!$s['view_all']) { $floor['power_entity'] = 'none'; $floor['utility_meters'] = null; }
|
||||
foreach ($floor['outdoor'] ?? [] as $i => $area) if (!$s['view_all']) {
|
||||
$floor['outdoor'][$i] = $this->maskRefs($area, $s['native_read']); $floor['outdoor'][$i]['area_id'] = null;
|
||||
}
|
||||
}
|
||||
unset($floor);
|
||||
if (!$s['view_all']) {
|
||||
$building['presence'] = []; $building['energy'] = []; $building['settings']['weather_variables'] = [];
|
||||
foreach ($building['settings'] as $key => $value) if (is_string($value) && $this->variableIdForEntity($value) !== null) $building['settings'][$key] = 'none';
|
||||
}
|
||||
return $building;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
/** Native Symcon 9.0 configuration. Password fields are actions, never persistent module properties. */
|
||||
trait NextFloorUsers
|
||||
{
|
||||
public function GetConfigurationForm(): string
|
||||
{
|
||||
$form = json_decode((string) file_get_contents(__DIR__ . '/../form.json'), true, 512, JSON_THROW_ON_ERROR);
|
||||
$id = $this->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 = static function (string $name, string $caption, array $options, array $values) use ($level): 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 ['type' => 'List', 'name' => $name, 'caption' => $caption, 'rowCount' => 5, 'add' => true, 'delete' => true, 'values' => $values,
|
||||
'columns' => [['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' => $level]]];
|
||||
};
|
||||
$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' => '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' => 'PasswordTextBox', 'name' => 'AccountPassword', 'caption' => 'Neues Passwort (leer = bestehendes behalten)', 'value' => ''],
|
||||
['type' => 'Button', 'caption' => 'Benutzer speichern', 'onClick' => 'echo NFSC_SaveAccessUser($id, $AccountSelect, $AccountName, $AccountRole, $AccountEnabled, $AccountViewAll, $AccountControlAll, json_encode($AccountRooms), json_encode($AccountDevices), json_encode($AccountObjects), $AccountPassword);'],
|
||||
['type' => 'Button', 'name' => 'AccountReset', 'caption' => 'Passwort zurücksetzen', 'enabled' => $id !== '', 'onClick' => 'echo NFSC_ResetUserPassword($id, $AccountSelect, $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' => '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;
|
||||
}
|
||||
|
||||
public function SelectAccessUser(string $UserID): void
|
||||
{
|
||||
$a = $this->accounts()[$UserID] ?? [];
|
||||
if (!$a) $UserID = '';
|
||||
$this->WriteAttributeString('SelectedAccount', $UserID);
|
||||
$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) $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.';
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user