Update hash-users.js
This commit is contained in:
1 parent
e814d85065
commit
61aff58d55
1 file changed
+29
-22
@@ -1,5 +1,5 @@
|
|||||||
// 用法: node scripts/hash-users.js
|
// 用法: node scripts/hash-users.js
|
||||||
// 生成哈希后的 users.json
|
// 读取 users.json 中的明文密码,哈希后写回
|
||||||
|
|
||||||
const { createHash, randomBytes } = require("crypto");
|
const { createHash, randomBytes } = require("crypto");
|
||||||
const fs = require("fs");
|
const fs = require("fs");
|
||||||
@@ -9,27 +9,34 @@ function hashPassword(password, salt) {
|
|||||||
return createHash("sha256").update(salt + password).digest("hex");
|
return createHash("sha256").update(salt + password).digest("hex");
|
||||||
}
|
}
|
||||||
|
|
||||||
// 在这里修改用户信息
|
const usersPath = path.join(__dirname, "..", "users.json");
|
||||||
const users = [
|
|
||||||
{ username: "admin", password: "admin123", name: "小赵", role: "admin" },
|
if (!fs.existsSync(usersPath)) {
|
||||||
{ username: "xiaomei", password: "xiaomei123", name: "小美", role: "user" },
|
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 salt = randomBytes(16).toString("hex");
|
||||||
const passwordHash = hashPassword(u.password, salt);
|
const passwordHash = hashPassword(user.password, salt);
|
||||||
return {
|
user.passwordHash = passwordHash;
|
||||||
username: u.username,
|
user.salt = salt;
|
||||||
passwordHash,
|
delete user.password;
|
||||||
salt,
|
changed = true;
|
||||||
name: u.name,
|
}
|
||||||
role: u.role,
|
|
||||||
};
|
|
||||||
});
|
|
||||||
|
|
||||||
const output = { users: hashedUsers };
|
if (changed) {
|
||||||
const outPath = path.join(__dirname, "..", "users.json");
|
fs.writeFileSync(usersPath, JSON.stringify(data, null, 2) + "\n");
|
||||||
fs.writeFileSync(outPath, JSON.stringify(output, null, 2) + "\n");
|
console.log("密码哈希完成");
|
||||||
|
} else {
|
||||||
console.log("已生成 users.json(密码已哈希)");
|
console.log("所有密码已哈希,无需处理");
|
||||||
console.log("用户名列表:", hashedUsers.map(u => u.username).join(", "));
|
}
|
||||||
Reference in new issue
Block a user