hardlounge/server/command-line/users/reset.ts

76 lines
1.8 KiB
TypeScript
Raw Normal View History

import log from "../../log";
import colors from "chalk";
import {Command} from "commander";
import fs from "fs";
import Helper from "../../helper";
import Config from "../../config";
import Utils from "../utils";
2014-09-11 21:00:08 +00:00
const program = new Command("reset");
2014-09-11 21:00:08 +00:00
program
.description("Reset user password")
.on("--help", Utils.extraHelp)
.argument("<name>", "name of the user")
.option("--password [password]", "new password, will be prompted if not specified")
.action(function (name, cmdObj) {
if (!fs.existsSync(Config.getUsersPath())) {
log.error(`${Config.getUsersPath()} does not exist.`);
return;
}
// eslint-disable-next-line @typescript-eslint/no-var-requires
const ClientManager = require("../../clientManager").default;
const users = new ClientManager().getUsers();
2019-07-17 09:33:59 +00:00
if (users === undefined) {
// There was an error, already logged
return;
}
if (!users.includes(name)) {
log.error(`User ${colors.bold(name)} does not exist.`);
2014-09-11 21:00:08 +00:00
return;
}
if (cmdObj.password) {
change(name, cmdObj.password);
return;
}
2019-07-17 09:33:59 +00:00
log.prompt(
{
text: "Enter new password:",
silent: true,
},
function (err, password) {
2019-07-17 09:33:59 +00:00
if (err) {
return;
}
change(name, password);
2019-07-17 09:33:59 +00:00
}
);
2014-09-11 21:00:08 +00:00
});
function change(name, password) {
const pathReal = Config.getUserConfigPath(name);
const pathTemp = pathReal + ".tmp";
const user = JSON.parse(fs.readFileSync(pathReal, "utf-8"));
user.password = Helper.password.hash(password);
user.sessions = {};
const newUser = JSON.stringify(user, null, "\t");
// Write to a temp file first, in case the write fails
// we do not lose the original file (for example when disk is full)
fs.writeFileSync(pathTemp, newUser, {
mode: 0o600,
});
fs.renameSync(pathTemp, pathReal);
log.info(`Successfully reset password for ${colors.bold(name)}.`);
}
export default program;