From 3e0699a2fe2785f48aef1fc25dadb0923a4153d9 Mon Sep 17 00:00:00 2001 From: hex2077 Date: Thu, 25 Dec 2025 18:10:06 +0800 Subject: [PATCH] =?UTF-8?q?refactor(auth):=20=E6=94=B9=E8=BF=9B=E5=AF=86?= =?UTF-8?q?=E7=A0=81=E6=96=87=E4=BB=B6=E8=AF=BB=E5=8F=96=E5=92=8C=E9=AA=8C?= =?UTF-8?q?=E8=AF=81=E9=80=BB=E8=BE=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 使用异步方式检查文件存在性避免竞态条件 - 增加详细的日志输出帮助调试 - 统一处理文件不存在和读取失败的情况 - 在验证函数中添加密码长度日志 --- src/ui-manager.js | 23 +++++++++++++++-------- 1 file changed, 15 insertions(+), 8 deletions(-) diff --git a/src/ui-manager.js b/src/ui-manager.js index 05a716a..9d5b085 100644 --- a/src/ui-manager.js +++ b/src/ui-manager.js @@ -207,25 +207,29 @@ const DEFAULT_PASSWORD = 'admin123'; /** * 读取密码文件内容 + * 如果文件不存在或读取失败,返回默认密码 */ async function readPasswordFile() { const pwdFilePath = path.join(process.cwd(), 'configs', 'pwd'); try { - if (!existsSync(pwdFilePath)) { - console.log('[Auth] 密码文件不存在,使用默认密码'); - return DEFAULT_PASSWORD; - } + // 使用异步方式检查文件是否存在并读取,避免竞态条件 const password = await fs.readFile(pwdFilePath, 'utf8'); const trimmedPassword = password.trim(); // 如果密码文件为空,使用默认密码 if (!trimmedPassword) { - console.log('[Auth] 密码文件为空,使用默认密码'); + console.log('[Auth] 密码文件为空,使用默认密码: ' + DEFAULT_PASSWORD); return DEFAULT_PASSWORD; } + console.log('[Auth] 成功读取密码文件'); return trimmedPassword; } catch (error) { - console.error('[Auth] 读取密码文件失败:', error.message); - console.log('[Auth] 使用默认密码'); + // ENOENT 表示文件不存在,这是正常情况 + if (error.code === 'ENOENT') { + console.log('[Auth] 密码文件不存在,使用默认密码: ' + DEFAULT_PASSWORD); + } else { + console.error('[Auth] 读取密码文件失败:', error.code || error.message); + console.log('[Auth] 使用默认密码: ' + DEFAULT_PASSWORD); + } return DEFAULT_PASSWORD; } } @@ -235,7 +239,10 @@ async function readPasswordFile() { */ async function validateCredentials(password) { const storedPassword = await readPasswordFile(); - return storedPassword && password === storedPassword; + console.log('[Auth] 验证密码, 存储密码长度:', storedPassword ? storedPassword.length : 0, ', 输入密码长度:', password ? password.length : 0); + const isValid = storedPassword && password === storedPassword; + console.log('[Auth] 密码验证结果:', isValid); + return isValid; } /**