Update hash-users.js

This commit is contained in:
Vaica committed 2026-06-22 15:20:20 +08:00
1 parent 7e9ea8a9d2
commit 8afb8a4756
1 file changed
+29 -22
+29 -22
View File
@@ -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("所有密码已哈希,无需处理");
}