From 61aff58d55e3fa446ae3085417f371ec0a9a2c2a Mon Sep 17 00:00:00 2001 From: Vaica <94612053+zqlit@users.noreply.github.com> Date: Mon, 22 Jun 2026 15:20:20 +0800 Subject: [PATCH] Update hash-users.js --- write-server/scripts/hash-users.js | 51 +++++++++++++++++------------- 1 file changed, 29 insertions(+), 22 deletions(-) diff --git a/write-server/scripts/hash-users.js b/write-server/scripts/hash-users.js index 22a1811a..dab4b8f6 100644 --- a/write-server/scripts/hash-users.js +++ b/write-server/scripts/hash-users.js @@ -1,5 +1,5 @@ // 用法: node scripts/hash-users.js -// 生成哈希后的 users.json +// 读取 users.json 中的明文密码,哈希后写回 const { createHash, randomBytes } = require("crypto"); const fs = require("fs"); @@ -9,27 +9,34 @@ function hashPassword(password, salt) { return createHash("sha256").update(salt + password).digest("hex"); } -// 在这里修改用户信息 -const users = [ - { username: "admin", password: "admin123", name: "小赵", role: "admin" }, - { username: "xiaomei", password: "xiaomei123", name: "小美", role: "user" }, -]; +const usersPath = path.join(__dirname, "..", "users.json"); + +if (!fs.existsSync(usersPath)) { + console.error("users.json 不存在"); + process.exit(1); +} + +const data = JSON.parse(fs.readFileSync(usersPath, "utf-8")); +const users = data.users || []; + +let changed = false; +for (const user of users) { + // 已经哈希过的跳过 + if (user.passwordHash && user.salt) continue; + // 没有明文密码的跳过 + if (!user.password) continue; -const hashedUsers = users.map(u => { const salt = randomBytes(16).toString("hex"); - const passwordHash = hashPassword(u.password, salt); - return { - username: u.username, - passwordHash, - salt, - name: u.name, - role: u.role, - }; -}); + const passwordHash = hashPassword(user.password, salt); + user.passwordHash = passwordHash; + user.salt = salt; + delete user.password; + changed = true; +} -const output = { users: hashedUsers }; -const outPath = path.join(__dirname, "..", "users.json"); -fs.writeFileSync(outPath, JSON.stringify(output, null, 2) + "\n"); - -console.log("已生成 users.json(密码已哈希)"); -console.log("用户名列表:", hashedUsers.map(u => u.username).join(", ")); +if (changed) { + fs.writeFileSync(usersPath, JSON.stringify(data, null, 2) + "\n"); + console.log("密码哈希完成"); +} else { + console.log("所有密码已哈希,无需处理"); +}