When updating user file, write to temp file first

This commit is contained in:
Pavel Djundik 2019-12-15 16:56:17 +02:00
parent 86341f063c
commit c1920eb566
2 changed files with 20 additions and 4 deletions

View file

@ -195,8 +195,15 @@ ClientManager.prototype.updateUser = function(name, opts, callback) {
return callback ? callback() : true;
}
const pathReal = Helper.getUserConfigPath(name);
const pathTemp = pathReal + ".tmp";
try {
fs.writeFileSync(Helper.getUserConfigPath(name), newUser);
// 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);
fs.renameSync(pathTemp, pathReal);
return callback ? callback() : true;
} catch (e) {
log.error(`Failed to update user ${colors.green(name)} (${e})`);

View file

@ -30,8 +30,10 @@ program
return;
}
const file = Helper.getUserConfigPath(name);
const user = require(file);
const pathReal = Helper.getUserConfigPath(name);
const pathTemp = pathReal + ".tmp";
const user = JSON.parse(fs.readFileSync(pathReal, "utf-8"));
log.prompt(
{
text: "Enter new password:",
@ -44,7 +46,14 @@ program
user.password = Helper.password.hash(password);
user.sessions = {};
fs.writeFileSync(file, JSON.stringify(user, null, "\t"));
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);
fs.renameSync(pathTemp, pathReal);
log.info(`Successfully reset password for ${colors.bold(name)}.`);
}
);