From 6d60814097d6d132f0e3fa45c46b6915794e7850 Mon Sep 17 00:00:00 2001 From: Andrei Smaliak Date: Thu, 23 Apr 2026 17:39:13 +0400 Subject: [PATCH] password change method added --- ENGINEER_INSTRUCTIONS.md | 48 ++++- stage_ui/console_core/backend/app.py | 85 ++++++++- stage_ui/console_core/frontend/console.css | 27 +++ .../console_core/frontend/console.i18n.js | 67 +++++++ stage_ui/console_core/frontend/console.js | 177 +++++++++++++++++- stage_ui/console_core/frontend/index.html | 1 + 6 files changed, 402 insertions(+), 3 deletions(-) diff --git a/ENGINEER_INSTRUCTIONS.md b/ENGINEER_INSTRUCTIONS.md index 89c69e9..4113dc2 100644 --- a/ENGINEER_INSTRUCTIONS.md +++ b/ENGINEER_INSTRUCTIONS.md @@ -18,6 +18,17 @@ install_iomatex_edge.sh scp -r install_iomatex_edge.sh youngfeel@ip.add.re.ss:/home/youngfeel/ ``` +Важно: эту команду нужно выполнять из той директории на laptop, где реально лежит файл `install_iomatex_edge.sh`. + +Например, если репозиторий скачан в `~/Iomatex_OS`, сначала перейдите туда: + +```bash +cd ~/Iomatex_OS +scp -r install_iomatex_edge.sh youngfeel@ip.add.re.ss:/home/youngfeel/ +``` + +Если выполнить `scp` из произвольной директории, где файла `install_iomatex_edge.sh` нет, копирование не сработает. + ## 2. Узнайте IP-адрес вашего Edge Самый простой способ: @@ -150,7 +161,42 @@ CTRL+C sudo iomatex-passwd ``` -## 8. Важно про reverse tunnel +## 8. Ручной запуск отдельной стадии + +Любая стадия, кроме `stage_env`, может быть выполнена отдельно вручную. + +`stage_env` не запускайте вручную отдельно как обычную стадию: она меняет базовое окружение, пользователей и reboot-flow. Для первичной установки используйте основной `install_iomatex_edge.sh`. + +Общий порядок ручного запуска стадии: + +1. скопируйте нужную директорию стадии на Edge; +2. подключитесь к Edge по SSH; +3. перейдите в скопированную директорию; +4. запустите install-скрипт стадии через `sudo bash`. + +Пример для `stage_ui`: + +```bash +scp -r stage_ui iomatex@ip.add.re.ss:/home/iomatex/ +ssh iomatex@ip.add.re.ss +cd /home/iomatex/stage_ui +sudo bash ./ui_installer.sh +``` + +Команду `scp -r stage_ui ...` также нужно выполнять из директории репозитория, где реально находится папка `stage_ui`. + +Типовые install-скрипты стадий: + +- `stage_wifi`: `sudo bash ./stage_wifi_install.sh` +- `stage_mqtt`: `sudo bash ./stage_mqtt_install.sh` +- `stage_ui`: `sudo bash ./ui_installer.sh` +- `stage_itscreen`: `sudo bash ./stage_itscreen_install.sh` +- `stage_reverse_tunnels`: `sudo bash ./stage_reverse_tunnels_install.sh` +- `stage_z2m`: `sudo bash ./stage_z2m_install` + +Если стадия зависит от файлов внутри своей директории, копируйте всю директорию стадии целиком, а не только один `.sh` файл. + +## 9. Важно про reverse tunnel Чтобы `reverse tunnel` начал работать, необходимо обратиться к sysadmin. diff --git a/stage_ui/console_core/backend/app.py b/stage_ui/console_core/backend/app.py index 4ffeabc..ffb5703 100644 --- a/stage_ui/console_core/backend/app.py +++ b/stage_ui/console_core/backend/app.py @@ -39,7 +39,7 @@ APP_DIR = "/opt/iomatex-console" PUBLIC_DIR = os.path.join(APP_DIR, "public") PROVIDERS_DIR = os.path.join(APP_DIR, "providers.d") CONFIG_PATH = "/etc/iomatex/console.json" -UI_VERSION = "V 2.2.7" +UI_VERSION = "V 2.2.10" DEFAULT_CONFIG = { "bind": "0.0.0.0", @@ -229,6 +229,18 @@ def delete_auth_session(token): _AUTH_SESSIONS.pop(value, None) +def delete_other_auth_sessions(username, keep_token): + user = str(username or "").strip() + keep = str(keep_token or "").strip() + with _AUTH_SESSIONS_LOCK: + stale = [ + token for token, session in _AUTH_SESSIONS.items() + if token != keep and str(session.get("username", "")).strip() == user + ] + for token in stale: + _AUTH_SESSIONS.pop(token, None) + + def build_session_cookie(token, max_age_sec): parts = [ f"{AUTH_COOKIE_NAME}={token}", @@ -244,6 +256,41 @@ def command_exists(name): return shutil.which(name) is not None +def password_policy_error(password): + secret = str(password or "") + if not secret: + return "New password is required" + if any(ch in secret for ch in ("\x00", "\r", "\n")): + return "Password contains unsupported characters" + if len(secret) < 8: + return "Password must be at least 8 characters long" + return "" + + +def change_system_password(username, new_password): + if not command_exists("passwd"): + return False, "passwd command is not available" + try: + proc = subprocess.run( + ["passwd", username], + input=f"{new_password}\n{new_password}\n", + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=True, + timeout=20, + check=False, + ) + except subprocess.TimeoutExpired: + return False, "Password change timed out" + except Exception as exc: + return False, str(exc) + + output = "\n".join(part for part in (proc.stdout.strip(), proc.stderr.strip()) if part).strip() + if proc.returncode != 0: + return False, output or "Password change failed" + return True, output or "Password changed successfully" + + def utc_now_iso(): return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()) @@ -2474,6 +2521,42 @@ class Handler(BaseHTTPRequestHandler): return if not self.require_auth(parsed): return + if parsed.path == "/api/auth/password/change": + payload = self.read_json_body() + if payload is None: + self.send_json({"ok": False, "error": "Invalid JSON body"}, code=400) + return + current_password = str(payload.get("current_password", "")) + new_password = str(payload.get("new_password", "")) + confirm_password = str(payload.get("confirm_password", "")) + session = getattr(self, "_auth_session", {}) or {} + username = str(session.get("username", AUTH_USERNAME)).strip() or AUTH_USERNAME + + if not current_password.strip(): + self.send_json({"ok": False, "error": "Current password is required"}, code=400) + return + if not verify_system_password(username, current_password): + self.send_json({"ok": False, "error": "Current password is incorrect"}, code=403) + return + if new_password != confirm_password: + self.send_json({"ok": False, "error": "Passwords do not match"}, code=400) + return + policy_error = password_policy_error(new_password) + if policy_error: + self.send_json({"ok": False, "error": policy_error}, code=400) + return + if current_password == new_password: + self.send_json({"ok": False, "error": "New password must be different from the current password"}, code=400) + return + + ok, message = change_system_password(username, new_password) + if not ok: + self.send_json({"ok": False, "error": message or "Password change failed"}, code=500) + return + delete_other_auth_sessions(username, self.parsed_cookies().get(AUTH_COOKIE_NAME)) + self.send_json({"ok": True, "message": "System password changed successfully"}) + return + if parsed.path == "/api/ap/password/change": payload = self.read_json_body() if payload is None: diff --git a/stage_ui/console_core/frontend/console.css b/stage_ui/console_core/frontend/console.css index b69a980..fb34794 100644 --- a/stage_ui/console_core/frontend/console.css +++ b/stage_ui/console_core/frontend/console.css @@ -805,6 +805,33 @@ html[dir="rtl"] .itscreenLogsActions{ .authSubmitBtn{ margin-top:4px; } +.authHelp{ + color:var(--muted); + font-size:13px; + line-height:1.45; +} +.authHelp summary{ + cursor:pointer; + font-weight:800; + color:var(--ink); +} +.authHelp ol{ + margin:8px 0 0; + padding-inline-start:20px; +} +.accountSecurityCard{ + align-content:start; +} +.accountPasswordForm{ + display:grid; + gap:12px; +} +.securitySteps{ + margin:0; + padding-inline-start:20px; + color:var(--ink); + line-height:1.55; +} .serviceActionRow{align-items:center} .actionBadge{ display:inline-flex;align-items:center;border-radius:999px;padding:6px 10px; diff --git a/stage_ui/console_core/frontend/console.i18n.js b/stage_ui/console_core/frontend/console.i18n.js index 44ba8f6..43bdd30 100644 --- a/stage_ui/console_core/frontend/console.i18n.js +++ b/stage_ui/console_core/frontend/console.i18n.js @@ -21,6 +21,7 @@ "Reboot": "Перезагрузить", "Switch theme": "Сменить тему", "Health": "Состояние", + "Security": "Безопасность", "Network": "Сеть", "It-Screen": "It-Screen", "G-Box Instructions and Manual": "Инструкции и руководство G-Box", @@ -228,6 +229,10 @@ "Local maintenance Wi-Fi": "Локальный сервисный Wi‑Fi", "Access Point creates a local Wi-Fi network on the device. It is used for first-time setup, maintenance, and recovery when the device cannot connect to the configured network.": "Access Point создаёт локальную Wi‑Fi сеть на устройстве. Она используется для первичной настройки, обслуживания и восстановления, когда устройство не может подключиться к настроенной сети.", "It usually turns on when the device has no working uplink or when an engineer enables AP mode for service access. In normal operation it may remain disabled.": "Обычно точка доступа включается, когда у устройства нет рабочего uplink-подключения или инженер вручную включает режим AP для обслуживания. В штатной работе она может оставаться выключенной.", + "Account security": "Безопасность аккаунта", + "Change the WEB UI login password for the local iomatex user.": "Изменение пароля входа в WEB UI для локального пользователя iomatex.", + "WEB UI account password management and recovery steps.": "Управление паролем аккаунта WEB UI и порядок восстановления.", + "If the WEB UI password is unknown, recovery is available only from the device with a connected monitor and keyboard.": "Если пароль WEB UI неизвестен, восстановление доступно только с самого устройства при подключённых мониторе и клавиатуре.", "Change password": "Изменить пароль", "Set custom password": "Установить пользовательский пароль", "Reset to factory password": "Сбросить на заводской пароль", @@ -237,6 +242,11 @@ "Hide": "Скрыть", "Show": "Показать", "Use at least 8 characters. Allowed symbols: lowercase letters and digits.": "Используйте не менее 8 символов. Разрешены строчные буквы и цифры.", + "Use at least 8 characters. System password policy is checked by the device.": "Используйте не менее 8 символов. Системная политика паролей проверяется устройством.", + "Forgot password?": "Забыли пароль?", + "Connect a monitor and keyboard to the Edge device.": "Подключите монитор и клавиатуру к устройству Edge.", + "Open a local terminal and run: sudo iomatex-passwd": "Откройте локальный терминал и выполните: sudo iomatex-passwd", + "Set a new password for the iomatex user, then sign in here with the new password.": "Задайте новый пароль для пользователя iomatex, затем войдите здесь с новым паролем.", "Applying...": "Применение...", "Apply": "Применить", "Reset returns Access Point authentication to deterministic factory mode.": "Сброс возвращает аутентификацию Access Point в детерминированный заводской режим.", @@ -388,7 +398,14 @@ "Access point password reset to factory mode.": "Пароль точки доступа сброшен в заводской режим.", "Failed to reset AP password": "Не удалось сбросить пароль точки доступа", "Current password is required": "Требуется текущий пароль", + "New password and confirmation are required": "Требуются новый пароль и подтверждение", + "Password must be at least 8 characters long": "Пароль должен содержать не менее 8 символов", "Password must be at least 8 characters long and contain only lowercase letters and digits": "Пароль должен содержать не менее 8 символов и включать только строчные буквы и цифры", + "Password contains unsupported characters": "Пароль содержит неподдерживаемые символы", + "New password must be different from the current password": "Новый пароль должен отличаться от текущего", + "Current password is incorrect": "Текущий пароль неверный", + "Password change failed": "Не удалось изменить пароль", + "System password changed successfully": "Системный пароль успешно изменён", "Passwords do not match": "Пароли не совпадают", "SSID is required": "Требуется SSID", "Please wait {seconds}s before scanning again.": "Подождите {seconds} с перед повторным сканированием.", @@ -410,6 +427,7 @@ "IOMATEX Console": "Konsola IOMATEX", "Switch theme": "Przełącz motyw", "Health": "Stan", + "Security": "Bezpieczeństwo", "Network": "Sieć", "It-Screen": "It-Screen", "G-Box Instructions and Manual": "Instrukcja i podręcznik G-Box", @@ -527,10 +545,18 @@ "Local maintenance Wi-Fi": "Lokalne serwisowe Wi‑Fi", "Access Point creates a local Wi-Fi network on the device. It is used for first-time setup, maintenance, and recovery when the device cannot connect to the configured network.": "Access Point tworzy lokalną sieć Wi‑Fi na urządzeniu. Służy do pierwszej konfiguracji, konserwacji i odzyskiwania, gdy urządzenie nie może połączyć się ze skonfigurowaną siecią.", "It usually turns on when the device has no working uplink or when an engineer enables AP mode for service access. In normal operation it may remain disabled.": "Zwykle włącza się, gdy urządzenie nie ma działającego łącza uplink lub gdy inżynier włącza tryb AP do serwisu. W normalnej pracy może pozostać wyłączony.", + "Account security": "Bezpieczeństwo konta", + "Change the WEB UI login password for the local iomatex user.": "Zmiana hasła logowania do WEB UI dla lokalnego użytkownika iomatex.", + "WEB UI account password management and recovery steps.": "Zarządzanie hasłem konta WEB UI i kroki odzyskiwania.", + "If the WEB UI password is unknown, recovery is available only from the device with a connected monitor and keyboard.": "Jeśli hasło WEB UI jest nieznane, odzyskiwanie jest dostępne tylko z urządzenia z podłączonym monitorem i klawiaturą.", "Enabled": "Włączone", "Disabled": "Wyłączone", "Custom": "Własne", "Factory": "Fabryczne", + "Forgot password?": "Nie pamiętasz hasła?", + "Connect a monitor and keyboard to the Edge device.": "Podłącz monitor i klawiaturę do urządzenia Edge.", + "Open a local terminal and run: sudo iomatex-passwd": "Otwórz lokalny terminal i uruchom: sudo iomatex-passwd", + "Set a new password for the iomatex user, then sign in here with the new password.": "Ustaw nowe hasło dla użytkownika iomatex, a następnie zaloguj się tutaj nowym hasłem.", "Set custom password": "Ustaw własne hasło", "Not installed": "Nie zainstalowano", "Edge API": "Edge API", @@ -658,7 +684,14 @@ "Live log stream disconnected": "Strumień logów na żywo został rozłączony", "No matches in current buffer.": "Brak dopasowań w bieżącym buforze.", "Current password is required": "Wymagane jest bieżące hasło", + "New password and confirmation are required": "Nowe hasło i potwierdzenie są wymagane", + "Password must be at least 8 characters long": "Hasło musi mieć co najmniej 8 znaków", "Password must be at least 8 characters long and contain only lowercase letters and digits": "Hasło musi mieć co najmniej 8 znaków i zawierać tylko małe litery oraz cyfry", + "Password contains unsupported characters": "Hasło zawiera nieobsługiwane znaki", + "New password must be different from the current password": "Nowe hasło musi różnić się od bieżącego", + "Current password is incorrect": "Bieżące hasło jest nieprawidłowe", + "Password change failed": "Nie udało się zmienić hasła", + "System password changed successfully": "Hasło systemowe zostało pomyślnie zmienione", "Passwords do not match": "Hasła nie są zgodne", "SSID is required": "SSID jest wymagane", "Failed to scan networks": "Nie udało się przeskanować sieci", @@ -782,6 +815,7 @@ "Reboot": "إعادة التشغيل", "Switch theme": "تبديل السمة", "Health": "الحالة", + "Security": "الأمان", "Network": "الشبكة", "It-Screen": "It-Screen", "G-Box Instructions and Manual": "دليل وتعليمات G-Box", @@ -872,6 +906,7 @@ "Leave empty for open network": "اتركه فارغاً للشبكة المفتوحة", "This uses the existing edge Wi-Fi setup flow and applies the profile through backend only.": "يستخدم هذا مسار إعداد Wi‑Fi الحالي في edge ويطبق الملف التعريفي عبر backend فقط.", "Use at least 8 characters. Allowed symbols: lowercase letters and digits.": "استخدم 8 أحرف على الأقل. الرموز المسموح بها: الأحرف الصغيرة والأرقام.", + "Use at least 8 characters. System password policy is checked by the device.": "استخدم 8 أحرف على الأقل. يتحقق الجهاز من سياسة كلمة مرور النظام.", "Reset returns Access Point authentication to deterministic factory mode.": "يعيد الضبط مصادقة Access Point إلى وضع المصنع المحدد.", "Available Networks": "الشبكات المتاحة", "Network Overview": "نظرة عامة على الشبكة", @@ -895,7 +930,14 @@ "Resume": "استئناف", "Clear view": "مسح العرض", "Current password is required": "كلمة المرور الحالية مطلوبة", + "New password and confirmation are required": "كلمة المرور الجديدة والتأكيد مطلوبان", + "Password must be at least 8 characters long": "يجب أن تتكون كلمة المرور من 8 أحرف على الأقل", "Password must be at least 8 characters long and contain only lowercase letters and digits": "يجب أن تتكون كلمة المرور من 8 أحرف على الأقل وأن تحتوي فقط على أحرف صغيرة وأرقام", + "Password contains unsupported characters": "كلمة المرور تحتوي على أحرف غير مدعومة", + "New password must be different from the current password": "يجب أن تختلف كلمة المرور الجديدة عن الحالية", + "Current password is incorrect": "كلمة المرور الحالية غير صحيحة", + "Password change failed": "فشل تغيير كلمة المرور", + "System password changed successfully": "تم تغيير كلمة مرور النظام بنجاح", "Passwords do not match": "كلمتا المرور غير متطابقتين", "SSID is required": "حقل SSID مطلوب", "Failed to scan networks": "فشل فحص الشبكات", @@ -975,6 +1017,14 @@ ,"Failed to copy VPS bootstrap command": "فشل نسخ أمر التهيئة الأولية لـ VPS" ,"To configure Reverse SSH access, connect to VPS with ssh builder@65.109.116.180, use the password from the sysadmin, then copy, paste, and run the script below by pressing Enter.": "لإعداد وصول Reverse SSH، اتصل بـ VPS عبر ssh builder@65.109.116.180، واستخدم كلمة المرور من مسؤول النظام، ثم انسخ السكربت أدناه والصقه وشغّله بالضغط على Enter." ,"Reverse Tunnel is needed for remote access from outside the local network. If you already have access to this UI, you are already on the same network as the Edge device, so Reverse Tunnel is usually not needed. To use it later, open Web UI, go to Devices, select your Edge device, then open the SSH tab in device settings. The required links and the full 2-step instructions are there.": "يلزم Reverse Tunnel للوصول عن بُعد من خارج الشبكة المحلية. إذا كان لديك وصول إلى هذا الـ UI بالفعل، فأنت ضمن نفس الشبكة مع جهاز Edge، لذلك غالباً لا تكون هناك حاجة إليه. لاستخدامه لاحقاً، افتح Web UI ثم اذهب إلى Devices واختر جهاز Edge الخاص بك وافتح تبويب SSH في إعدادات الجهاز. ستجد هناك الروابط المطلوبة والتعليمات الكاملة من خطوتين." + ,"Account security": "أمان الحساب" + ,"Change the WEB UI login password for the local iomatex user.": "تغيير كلمة مرور تسجيل الدخول إلى WEB UI للمستخدم المحلي iomatex." + ,"WEB UI account password management and recovery steps.": "إدارة كلمة مرور حساب WEB UI وخطوات الاسترداد." + ,"If the WEB UI password is unknown, recovery is available only from the device with a connected monitor and keyboard.": "إذا كانت كلمة مرور WEB UI غير معروفة، فلا يتوفر الاسترداد إلا من الجهاز نفسه مع توصيل شاشة ولوحة مفاتيح." + ,"Forgot password?": "هل نسيت كلمة المرور؟" + ,"Connect a monitor and keyboard to the Edge device.": "وصّل شاشة ولوحة مفاتيح بجهاز Edge." + ,"Open a local terminal and run: sudo iomatex-passwd": "افتح طرفية محلية وشغّل: sudo iomatex-passwd" + ,"Set a new password for the iomatex user, then sign in here with the new password.": "عيّن كلمة مرور جديدة للمستخدم iomatex، ثم سجّل الدخول هنا باستخدام كلمة المرور الجديدة." ,"HDMI audio": "صوت HDMI" ,"Analog audio": "الصوت التناظري" ,"Manufacturer": "الشركة المصنعة" @@ -1154,6 +1204,7 @@ "Reboot": "रीबूट", "Switch theme": "थीम बदलें", "Health": "स्थिति", + "Security": "सुरक्षा", "Network": "नेटवर्क", "It-Screen": "It-Screen", "G-Box Instructions and Manual": "G-Box निर्देश और मैनुअल", @@ -1246,6 +1297,14 @@ "Local maintenance Wi-Fi": "स्थानीय मेंटेनेंस Wi‑Fi", "Access Point creates a local Wi-Fi network on the device. It is used for first-time setup, maintenance, and recovery when the device cannot connect to the configured network.": "Access Point डिवाइस पर लोकल Wi‑Fi नेटवर्क बनाता है। इसका उपयोग पहली बार सेटअप, maintenance और recovery के लिए होता है, जब डिवाइस configured नेटवर्क से कनेक्ट नहीं हो पाता।", "It usually turns on when the device has no working uplink or when an engineer enables AP mode for service access. In normal operation it may remain disabled.": "यह आमतौर पर तब चालू होता है जब डिवाइस के पास working uplink न हो या service access के लिए engineer AP mode चालू करे। सामान्य स्थिति में यह बंद रह सकता है।", + "Account security": "खाता सुरक्षा", + "Change the WEB UI login password for the local iomatex user.": "स्थानीय iomatex उपयोगकर्ता के लिए WEB UI लॉगिन पासवर्ड बदलें।", + "WEB UI account password management and recovery steps.": "WEB UI खाते के पासवर्ड प्रबंधन और रिकवरी चरण।", + "If the WEB UI password is unknown, recovery is available only from the device with a connected monitor and keyboard.": "यदि WEB UI पासवर्ड ज्ञात नहीं है, तो रिकवरी केवल कनेक्टेड मॉनिटर और कीबोर्ड वाले डिवाइस से उपलब्ध है।", + "Forgot password?": "पासवर्ड भूल गए?", + "Connect a monitor and keyboard to the Edge device.": "Edge डिवाइस से मॉनिटर और कीबोर्ड कनेक्ट करें।", + "Open a local terminal and run: sudo iomatex-passwd": "स्थानीय टर्मिनल खोलें और चलाएँ: sudo iomatex-passwd", + "Set a new password for the iomatex user, then sign in here with the new password.": "iomatex उपयोगकर्ता के लिए नया पासवर्ड सेट करें, फिर यहाँ नए पासवर्ड से साइन इन करें।", "Enabled": "सक्षम", "Disabled": "बंद", "Custom": "कस्टम", @@ -1273,6 +1332,7 @@ "Leave empty for open network": "ओपन नेटवर्क के लिए खाली छोड़ें", "This uses the existing edge Wi-Fi setup flow and applies the profile through backend only.": "यह existing edge Wi‑Fi setup flow का उपयोग करता है और प्रोफ़ाइल केवल backend के माध्यम से लागू करता है।", "Use at least 8 characters. Allowed symbols: lowercase letters and digits.": "कम से कम 8 अक्षर उपयोग करें। मान्य चिन्ह: छोटे अक्षर और अंक।", + "Use at least 8 characters. System password policy is checked by the device.": "कम से कम 8 अक्षर उपयोग करें। सिस्टम पासवर्ड नीति डिवाइस द्वारा जाँची जाती है।", "Reset returns Access Point authentication to deterministic factory mode.": "Reset करने पर Access Point authentication फैक्टरी mode में लौट जाती है।", "Current password": "वर्तमान पासवर्ड", "New password": "नया पासवर्ड", @@ -1395,7 +1455,14 @@ "Live log stream disconnected": "Live log stream डिस्कनेक्ट हो गया", "No matches in current buffer.": "वर्तमान buffer में कोई match नहीं मिला।", "Current password is required": "वर्तमान पासवर्ड आवश्यक है", + "New password and confirmation are required": "नया पासवर्ड और पुष्टि आवश्यक हैं", + "Password must be at least 8 characters long": "पासवर्ड कम से कम 8 अक्षरों का होना चाहिए", "Password must be at least 8 characters long and contain only lowercase letters and digits": "पासवर्ड कम से कम 8 अक्षरों का होना चाहिए और उसमें केवल छोटे अक्षर और अंक होने चाहिए", + "Password contains unsupported characters": "पासवर्ड में असमर्थित अक्षर हैं", + "New password must be different from the current password": "नया पासवर्ड वर्तमान पासवर्ड से अलग होना चाहिए", + "Current password is incorrect": "वर्तमान पासवर्ड गलत है", + "Password change failed": "पासवर्ड बदलना विफल रहा", + "System password changed successfully": "सिस्टम पासवर्ड सफलतापूर्वक बदल गया", "Passwords do not match": "पासवर्ड मेल नहीं खाते", "SSID is required": "SSID आवश्यक है", "Failed to scan networks": "नेटवर्क स्कैन नहीं हो सका", diff --git a/stage_ui/console_core/frontend/console.js b/stage_ui/console_core/frontend/console.js index 00d7fa2..d005069 100644 --- a/stage_ui/console_core/frontend/console.js +++ b/stage_ui/console_core/frontend/console.js @@ -24,6 +24,7 @@ refreshMenuLabel: document.getElementById("refreshMenuLabel"), rebootMenuLabel: document.getElementById("rebootMenuLabel"), tabHealth: document.getElementById("tabHealth"), + tabSecurity: document.getElementById("tabSecurity"), tabNetwork: document.getElementById("tabNetwork"), tabModbus: document.getElementById("tabModbus"), tabTscreen: document.getElementById("tabTscreen"), @@ -43,7 +44,7 @@ { mode: "test_by", label: "TEST BY", host: "rest.test.it-screen.by" }, { mode: "custom", label: "Custom", host: "" } ]; - const UI_VERSION = "V 2.2.7"; + const UI_VERSION = "V 2.2.10"; const ITSCREEN_LOG_INITIAL_LINES = 50; const ITSCREEN_LOG_BUFFER_LIMIT = 300; const ITSCREEN_LOG_BATCH_MS = 250; @@ -280,6 +281,17 @@ info: "", expiresAt: 0 }, + accountPassword: { + busy: false, + message: "", + error: "", + currentPassword: "", + newPassword: "", + confirmPassword: "", + showCurrentPassword: false, + showNewPassword: false, + showConfirmPassword: false + }, menuOpen: false, rebootPending: false, isPolling: false @@ -488,6 +500,7 @@ if (nodes.rebootMenuLabel) nodes.rebootMenuLabel.textContent = t("Reboot"); if (nodes.logoutMenuLabel) nodes.logoutMenuLabel.textContent = t("Logout"); if (nodes.tabHealth) nodes.tabHealth.textContent = t("Health"); + if (nodes.tabSecurity) nodes.tabSecurity.textContent = t("Security"); if (nodes.tabNetwork) nodes.tabNetwork.textContent = t("Network"); if (nodes.tabModbus) nodes.tabModbus.textContent = t("Modbus"); if (nodes.tabTscreen) nodes.tabTscreen.textContent = t("It-Screen"); @@ -559,6 +572,7 @@ state.auth.info = message || t("Authorization required"); state.auth.expiresAt = 0; state.itscreen.loading = false; + resetAccountPasswordForm(false); deactivateItscreenLogs({ status: "disconnected" }); closeActionMenu(); setPrimaryUiLocked(true); @@ -579,6 +593,19 @@ syncActionMenu(); } + function resetAccountPasswordForm(keepMessage) { + const account = state.accountPassword; + account.busy = false; + account.error = ""; + if (!keepMessage) account.message = ""; + account.currentPassword = ""; + account.newPassword = ""; + account.confirmPassword = ""; + account.showCurrentPassword = false; + account.showNewPassword = false; + account.showConfirmPassword = false; + } + function applyTheme(theme) { state.theme = theme === "dark" ? "dark" : "light"; document.documentElement.setAttribute("data-theme", state.theme); @@ -1599,6 +1626,92 @@ `; } + function accountPasswordValidationError() { + const account = state.accountPassword; + if (!account.currentPassword.trim()) return t("Current password is required"); + if (!account.newPassword || !account.confirmPassword) return t("New password and confirmation are required"); + if (account.newPassword !== account.confirmPassword) return t("Passwords do not match"); + if (account.newPassword.length < 8) return t("Password must be at least 8 characters long"); + if (account.currentPassword === account.newPassword) return t("New password must be different from the current password"); + return ""; + } + + function renderAccountPasswordInput(field, label, autocomplete, visibleField) { + const account = state.accountPassword; + const visible = !!account[visibleField]; + const disabled = account.busy; + return ` + + `; + } + + function renderAccountSecurityPanel() { + const account = state.accountPassword; + return ` +
+
+
+

${esc(t("Account security"))}

+

${esc(t("Change the WEB UI login password for the local iomatex user."))}

+
+
+
+
${esc(t("Username"))}
${esc(state.auth.username || "iomatex")}
+
+
+ ${renderAccountPasswordInput("currentPassword", t("Current password"), "current-password", "showCurrentPassword")} + ${renderAccountPasswordInput("newPassword", t("New password"), "new-password", "showNewPassword")} + ${renderAccountPasswordInput("confirmPassword", t("Confirm new password"), "new-password", "showConfirmPassword")} +
${esc(t("Use at least 8 characters. System password policy is checked by the device."))}
+ ${account.message ? `` : ""} + ${account.error ? `` : ""} +
+ +
+
+
+ `; + } + + function renderPasswordRecoveryPanel() { + return ` +
+
+
+

${esc(t("Forgot password?"))}

+

${esc(t("If the WEB UI password is unknown, recovery is available only from the device with a connected monitor and keyboard."))}

+
+
+
    +
  1. ${esc(t("Connect a monitor and keyboard to the Edge device."))}
  2. +
  3. ${esc(t("Open a local terminal and run: sudo iomatex-passwd"))}
  4. +
  5. ${esc(t("Set a new password for the iomatex user, then sign in here with the new password."))}
  6. +
+
+ `; + } + + function renderSecurityTab() { + return ` +
+
+

${esc(t("Security"))}

+

${esc(t("WEB UI account password management and recovery steps."))}

+
+
+ ${renderAccountSecurityPanel()} + ${renderPasswordRecoveryPanel()} +
+
+ `; + } + function renderHealthTab() { const payload = state.healthServices || { services: [] }; const health = state.health || {}; @@ -3356,6 +3469,10 @@ updateApFormUi(); return; } + if (state.activeTab === "security") { + nodes.content.innerHTML = renderSecurityTab(); + return; + } if (state.activeTab === "modbus") { captureModbusScanLogViewport(); nodes.content.innerHTML = renderModbusTab(); @@ -3415,6 +3532,14 @@ ${infoMessage ? `` : ""} ${errorMessage ? `` : ""} +
+ ${esc(t("Forgot password?"))} +
    +
  1. ${esc(t("Connect a monitor and keyboard to the Edge device."))}
  2. +
  3. ${esc(t("Open a local terminal and run: sudo iomatex-passwd"))}
  4. +
  5. ${esc(t("Set a new password for the iomatex user, then sign in here with the new password."))}
  6. +
+
@@ -4782,6 +4907,56 @@ renderActiveTab(); }; + window.__accountPasswordSetField = function (field, value) { + if (!Object.prototype.hasOwnProperty.call(state.accountPassword, field)) return; + state.accountPassword[field] = (value ?? "").toString(); + state.accountPassword.error = ""; + state.accountPassword.message = ""; + }; + + window.__accountPasswordToggle = function (field) { + if (!Object.prototype.hasOwnProperty.call(state.accountPassword, field)) return; + state.accountPassword[field] = !state.accountPassword[field]; + renderActiveTab(); + }; + + window.__accountPasswordSubmit = async function (event) { + if (event && typeof event.preventDefault === "function") event.preventDefault(); + const account = state.accountPassword; + if (account.busy) return; + const validationError = accountPasswordValidationError(); + if (validationError) { + account.error = validationError; + account.message = ""; + renderActiveTab(); + return; + } + account.busy = true; + account.error = ""; + account.message = ""; + renderActiveTab(); + try { + const payload = await fetchJson("/api/auth/password/change", { + method: "POST", + cache: "no-store", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + current_password: account.currentPassword, + new_password: account.newPassword, + confirm_password: account.confirmPassword + }) + }); + account.message = translateUiText(payload.message || t("System password changed successfully")); + resetAccountPasswordForm(true); + showToast("success", account.message); + } catch (error) { + account.busy = false; + account.error = translateUiText(error.message || t("Password change failed")); + } finally { + if (state.activeTab === "health") renderActiveTab(); + } + }; + window.__authSubmit = async function (event) { if (event && typeof event.preventDefault === "function") event.preventDefault(); if (state.auth.busy || state.auth.loading) return; diff --git a/stage_ui/console_core/frontend/index.html b/stage_ui/console_core/frontend/index.html index 8090674..4c6bc93 100644 --- a/stage_ui/console_core/frontend/index.html +++ b/stage_ui/console_core/frontend/index.html @@ -88,6 +88,7 @@