Restore password policy editing in Web Console
This commit is contained in:
1 parent
bf3b40d9a5
commit
4801cfbe77
6 files changed
+174
-25
No files matched your search
@@ -4,7 +4,7 @@ const element = (id) => document.getElementById(id);
|
||||
const routes = ["overview", "storage", "security", "audit"];
|
||||
const nav = [...document.querySelectorAll("nav button")];
|
||||
const dateFormat = new Intl.DateTimeFormat("ru", { dateStyle: "short", timeStyle: "short" });
|
||||
const labels = { LOGIN: "Вход", LOGOUT: "Выход" };
|
||||
const labels = { LOGIN: "Вход", LOGOUT: "Выход", SETTINGS: "Настройки" };
|
||||
const pageSize = 20;
|
||||
let token = "";
|
||||
let revision = 0;
|
||||
@@ -149,6 +149,54 @@ function definitions(target, entries) {
|
||||
}
|
||||
|
||||
const yesNo = (value) => value === "true" ? "Да" : value === "false" ? "Нет" : "—";
|
||||
const policyForm = element("policy");
|
||||
const policyInputs = [...policyForm.querySelectorAll("input[name], select[name]")];
|
||||
for (const [name, options] of Object.entries({
|
||||
minimumLength: Array.from({ length: 13 }, (_, index) => index + 8),
|
||||
expirationDaysAfter: [30, 60, 90, 120, 150, 180],
|
||||
expirationReminderDaysBefore: Array.from({ length: 10 }, (_, index) => index + 1)
|
||||
})) {
|
||||
policyForm.elements[name].replaceChildren(...options.map((value) => new Option(value, value)));
|
||||
}
|
||||
|
||||
function updateExpirationFields() {
|
||||
const enabled = policyForm.elements.isExpirationEnabled.checked;
|
||||
policyForm.elements.expirationDaysAfter.disabled = !enabled;
|
||||
policyForm.elements.expirationReminderDaysBefore.disabled = !enabled;
|
||||
}
|
||||
|
||||
policyForm.elements.isExpirationEnabled.addEventListener("change", updateExpirationFields);
|
||||
policyForm.addEventListener("input", () => message("policy-feedback", ""));
|
||||
policyForm.addEventListener("submit", async (event) => {
|
||||
event.preventDefault();
|
||||
const feedback = element("policy-feedback");
|
||||
feedback.dataset.error = "true";
|
||||
if (policyInputs.filter((field) => field.name.endsWith("Enabled") &&
|
||||
field.name !== "isExpirationEnabled" && field.checked).length < 2) {
|
||||
message("policy-feedback", "Выберите не менее двух типов символов.");
|
||||
return;
|
||||
}
|
||||
const data = policyInputs.map((field) => ({
|
||||
section: "PasswordPolicy",
|
||||
key: field.name,
|
||||
value: field.type === "checkbox" ? String(field.checked) : field.value
|
||||
}));
|
||||
const fields = element("policy-fields");
|
||||
const requestToken = token;
|
||||
fields.disabled = true;
|
||||
message("policy-feedback", "");
|
||||
try {
|
||||
await api("/api/v1/settings/settingvalues", { data });
|
||||
if (requestToken !== token) return;
|
||||
feedback.dataset.error = "false";
|
||||
message("policy-feedback", "Политика сохранена.");
|
||||
} catch (error) {
|
||||
if (requestToken === token) message("policy-feedback", error.message);
|
||||
} finally {
|
||||
if (requestToken === token) fields.disabled = false;
|
||||
}
|
||||
});
|
||||
|
||||
const loaders = {
|
||||
async overview(active) {
|
||||
const [health, result] = await Promise.all([api("/health"), api("/api/v1/info/versions")]);
|
||||
@@ -169,6 +217,8 @@ const loaders = {
|
||||
element("copy-path").disabled = !storagePath;
|
||||
},
|
||||
async security(active) {
|
||||
element("policy-fields").disabled = true;
|
||||
message("policy-feedback", "");
|
||||
const [policy, protection, counts] = await Promise.all([
|
||||
api("/api/v1/settings/settingvalues/section/PasswordPolicy"),
|
||||
api("/api/v1/settings/settingvaluesp2/section/ProtectPatientSocialIDs/key/isEnabled"),
|
||||
@@ -176,14 +226,12 @@ const loaders = {
|
||||
]);
|
||||
if (!active()) return;
|
||||
const values = Object.fromEntries(policy.data.map(({ key, value }) => [key, value]));
|
||||
definitions("policy", [
|
||||
["Минимальная длина", values.minimumLength],
|
||||
["Прописные буквы", yesNo(values.isUpperAlphabetsEnabled)],
|
||||
["Строчные буквы", yesNo(values.isLowerAlphabetsEnabled)],
|
||||
["Цифры", yesNo(values.isNumericDigitsEnabled)],
|
||||
["Специальные символы", yesNo(values.isSpecialCharactersEnabled)],
|
||||
["Срок действия", yesNo(values.isExpirationEnabled)]
|
||||
]);
|
||||
for (const field of policyInputs) {
|
||||
if (field.type === "checkbox") field.checked = values[field.name] === "true";
|
||||
else field.value = values[field.name];
|
||||
}
|
||||
element("policy-fields").disabled = false;
|
||||
updateExpirationFields();
|
||||
definitions("privacy", [
|
||||
["Защита включена", yesNo(protection.data[0]?.value)],
|
||||
["Защищено", counts.protectedSocialIDs],
|
||||
|
||||
@@ -66,7 +66,25 @@
|
||||
<h1 id="security-title" tabindex="-1">Безопасность</h1>
|
||||
<div class="detail-grid">
|
||||
<article class="card detail"><h2>Политика паролей</h2><p class="muted">Требования оригинального EzServer к новым паролям</p>
|
||||
<dl id="policy"></dl>
|
||||
<form id="policy" class="policy">
|
||||
<fieldset id="policy-fields" disabled>
|
||||
<label>Минимальная длина<select name="minimumLength" required></select></label>
|
||||
<fieldset class="policy-toggles">
|
||||
<legend>Типы символов (не менее двух)</legend>
|
||||
<label><input type="checkbox" name="isUpperAlphabetsEnabled"> Прописные буквы</label>
|
||||
<label><input type="checkbox" name="isLowerAlphabetsEnabled"> Строчные буквы</label>
|
||||
<label><input type="checkbox" name="isNumericDigitsEnabled"> Цифры</label>
|
||||
<label><input type="checkbox" name="isSpecialCharactersEnabled"> Специальные символы</label>
|
||||
</fieldset>
|
||||
<label class="policy-switch"><input type="checkbox" name="isExpirationEnabled"> Ограничить срок действия</label>
|
||||
<div class="policy-period">
|
||||
<label>Срок, дней<select name="expirationDaysAfter"></select></label>
|
||||
<label>Напомнить за, дней<select name="expirationReminderDaysBefore"></select></label>
|
||||
</div>
|
||||
<button class="filled" type="submit">Сохранить</button>
|
||||
</fieldset>
|
||||
<p id="policy-feedback" role="status" hidden></p>
|
||||
</form>
|
||||
</article>
|
||||
<article class="card detail"><h2>Защита идентификаторов</h2><dl id="privacy"></dl></article>
|
||||
</div>
|
||||
|
||||
@@ -115,3 +115,14 @@ dd { margin: 0; font-weight: 600; text-align: end; }
|
||||
.filters label { flex: 1 1 9rem; }
|
||||
.topbar { font-size: .9rem; }
|
||||
}
|
||||
|
||||
.policy fieldset { border: 0; padding: 0; margin: 0; min-width: 0; }
|
||||
.policy > fieldset { display: grid; gap: 16px; }
|
||||
.policy .policy-toggles { display: grid; gap: 8px; }
|
||||
.policy legend { color: var(--muted); font-size: .875rem; margin-bottom: 8px; }
|
||||
.policy .policy-switch, .policy-toggles label { display: flex; align-items: center; gap: 10px; }
|
||||
.policy input[type="checkbox"] { width: 18px; height: 18px; min-height: 0; margin: 0; accent-color: var(--primary); }
|
||||
.policy-period { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 12px; }
|
||||
.policy button { justify-self: start; }
|
||||
#policy-feedback { margin: 12px 0 0; color: var(--ok); }
|
||||
#policy-feedback[data-error="true"] { color: var(--error); }
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
В строке меню доступны запуск и остановка, выбор порта, выбор папки снимков и кнопка для открытия `/webconsole`. Путь и порт меняются при остановленной службе. При выборе папки EzServer копирует снимки в новый подкаталог `Files` и сохраняет прежнюю копию. По умолчанию SQLite и снимки находятся в `~/Library/Application Support/EzServerMac`. Для командной строки отдельную папку снимков можно задать абсолютным путём в `EZSERVER_IMAGES_PARENT`.
|
||||
|
||||
Web Console приложения использует Material Design 3 и входит в каждую сборку. Локальный вход выполняется под `Master Admin` с паролем `0000` по умолчанию. Для запуска с другим паролем задайте `EZSERVER_CONSOLE_PASSWORD`. В консоли доступны обзор API, путь снимков, сведения о защите и журнал входов и выходов текущего процесса. Порт и папка меняются из строки меню. Отдельный PHP-режим раздаёт оригинальные статические ресурсы из установщика.
|
||||
Web Console приложения использует Material Design 3 и входит в каждую сборку. Локальный вход выполняется под `Master Admin` с паролем `0000` по умолчанию. Для запуска с другим паролем задайте `EZSERVER_CONSOLE_PASSWORD`. В консоли доступны обзор API, путь снимков, сведения о защите и журнал входов и выходов текущего процесса. Политику для новых паролей можно изменить во вкладке «Безопасность». Настройки хранятся в SQLite. Порт и папка меняются из строки меню. Отдельный PHP-режим раздаёт оригинальные статические ресурсы из установщика.
|
||||
|
||||
## Импорт из EzDent
|
||||
|
||||
|
||||
@@ -55,12 +55,69 @@ final class ServerStore {
|
||||
PRAGMA user_version = 1;
|
||||
""")
|
||||
}
|
||||
try execute("""
|
||||
CREATE TABLE IF NOT EXISTS password_policy (
|
||||
key TEXT PRIMARY KEY NOT NULL,
|
||||
value TEXT NOT NULL
|
||||
);
|
||||
""")
|
||||
try recoverPendingDeletes()
|
||||
}
|
||||
}
|
||||
|
||||
deinit { sqlite3_close(db) }
|
||||
|
||||
private static let passwordPolicyDefaults = [
|
||||
"minimumLength": "10",
|
||||
"isUpperAlphabetsEnabled": "true",
|
||||
"isLowerAlphabetsEnabled": "true",
|
||||
"isNumericDigitsEnabled": "true",
|
||||
"isSpecialCharactersEnabled": "true",
|
||||
"isExpirationEnabled": "false",
|
||||
"expirationDaysAfter": "180",
|
||||
"expirationReminderDaysBefore": "10",
|
||||
]
|
||||
|
||||
private static let characterClasses = [
|
||||
"isUpperAlphabetsEnabled", "isLowerAlphabetsEnabled",
|
||||
"isNumericDigitsEnabled", "isSpecialCharactersEnabled",
|
||||
]
|
||||
|
||||
func passwordPolicy() throws -> [String: String] {
|
||||
lock.lock()
|
||||
defer { lock.unlock() }
|
||||
let rows = try query("SELECT key, value FROM password_policy") { row in
|
||||
(self.text(row, 0), self.text(row, 1))
|
||||
}
|
||||
let saved = Dictionary(uniqueKeysWithValues: rows)
|
||||
return Self.passwordPolicyDefaults.merging(saved) { _, value in value }
|
||||
}
|
||||
|
||||
func updatePasswordPolicy(_ changes: [String: String]) throws {
|
||||
lock.lock()
|
||||
defer { lock.unlock() }
|
||||
guard !changes.isEmpty, changes.keys.allSatisfy({ Self.passwordPolicyDefaults[$0] != nil }) else {
|
||||
throw StoreError.invalid
|
||||
}
|
||||
try transaction {
|
||||
let policy = try passwordPolicy().merging(changes) { _, value in value }
|
||||
let booleanKeys = Self.characterClasses + ["isExpirationEnabled"]
|
||||
guard let length = policy["minimumLength"].flatMap(Int.init), (8...20).contains(length),
|
||||
let days = policy["expirationDaysAfter"].flatMap(Int.init), (30...180).contains(days), days % 30 == 0,
|
||||
let reminder = policy["expirationReminderDaysBefore"].flatMap(Int.init), (1...10).contains(reminder),
|
||||
booleanKeys.allSatisfy({ policy[$0] == "true" || policy[$0] == "false" }),
|
||||
Self.characterClasses.filter({ policy[$0] == "true" }).count >= 2 else {
|
||||
throw StoreError.invalid
|
||||
}
|
||||
for (key, value) in changes {
|
||||
try run("""
|
||||
INSERT INTO password_policy(key, value) VALUES (?, ?)
|
||||
ON CONFLICT(key) DO UPDATE SET value = excluded.value
|
||||
""", [.text(key), .text(value)])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func copyImages(to parent: URL) throws {
|
||||
lock.lock()
|
||||
defer { lock.unlock() }
|
||||
|
||||
@@ -87,20 +87,35 @@ final class WebConsoleAPI {
|
||||
guard path == ["settings", "settingvalues", "section", "passwordpolicy"] else {
|
||||
return Reply(["data": []], errorCode: -100037)
|
||||
}
|
||||
// Display the defaults from CreateSETTINGDBTable.sql.
|
||||
let policy = [
|
||||
"minimumLength": "10",
|
||||
"isUpperAlphabetsEnabled": "true",
|
||||
"isLowerAlphabetsEnabled": "true",
|
||||
"isNumericDigitsEnabled": "true",
|
||||
"isSpecialCharactersEnabled": "true",
|
||||
"isExpirationEnabled": "false",
|
||||
"expirationDaysAfter": "180",
|
||||
"expirationReminderDaysBefore": "10",
|
||||
]
|
||||
return Reply(["data": policy.sorted { $0.key < $1.key }.map {
|
||||
["section": "PasswordPolicy", "key": $0.key, "value": $0.value]
|
||||
}])
|
||||
do {
|
||||
let policy = try store.passwordPolicy()
|
||||
return Reply(["data": policy.sorted { $0.key < $1.key }.map {
|
||||
["section": "PasswordPolicy", "key": $0.key, "value": $0.value]
|
||||
}])
|
||||
} catch {
|
||||
return Reply(status: "503 Service Unavailable", errorCode: -1005)
|
||||
}
|
||||
case ("settings", "settingvalues", "POST") where path.count == 2:
|
||||
guard let rows = input["data"] as? [[String: String]], (1...8).contains(rows.count) else {
|
||||
return Reply(status: "400 Bad Request", errorCode: -1021)
|
||||
}
|
||||
var changes: [String: String] = [:]
|
||||
for row in rows {
|
||||
guard row["section"] == "PasswordPolicy", let key = row["key"],
|
||||
let value = row["value"], changes[key] == nil else {
|
||||
return Reply(status: "400 Bad Request", errorCode: -1021)
|
||||
}
|
||||
changes[key] = value
|
||||
}
|
||||
do {
|
||||
try store.updatePasswordPolicy(changes)
|
||||
event(type: "SETTINGS", message: "Updated password policy.")
|
||||
return Reply()
|
||||
} catch StoreError.invalid {
|
||||
return Reply(status: "400 Bad Request", errorCode: -1021)
|
||||
} catch {
|
||||
return Reply(status: "503 Service Unavailable", errorCode: -1005)
|
||||
}
|
||||
case ("settings", "settingvaluesp2", "GET"):
|
||||
guard path == ["settings", "settingvaluesp2", "section", "protectpatientsocialids", "key", "isenabled"] else {
|
||||
return Reply(["data": []], errorCode: -100037)
|
||||
|
||||
Reference in new issue
Block a user