image_node/user.js

85 lines
1.8 KiB
JavaScript
Raw Normal View History

2020-04-28 22:31:57 +02:00
let readline = require("readline")
2020-04-26 20:12:50 +02:00
let fs = require("fs");
let passwordHash = require('password-hash');
2020-04-28 22:31:57 +02:00
function getFile() {
if (fs.existsSync("users.json")) {
file = JSON.parse(fs.readFileSync("users.json"));
} else {
fs.writeFileSync("users.json", "{}");
file = {};
}
return file;
}
function getReadLine() {
return readline.createInterface({input: process.stdin, output: process.stdout, terminal: false});
}
async function getUsername() {
let rl = getReadLine();
2020-04-26 20:12:50 +02:00
let username;
2020-04-28 22:31:57 +02:00
let file = getFile();
while (true) {
2020-04-26 20:12:50 +02:00
username = await new Promise(resolve => rl.question("Username: ", resolve));
2020-04-28 22:31:57 +02:00
if (username in file || ["", null].indexOf(username) >= 0)
2020-04-28 22:48:50 +02:00
console.error("Invalid username !");
2020-04-28 22:31:57 +02:00
else
break;
}
rl.close();
return username;
}
async function getPassword() {
let rl = getReadLine();
let password = await new Promise(resolve => rl.question("Password: ", resolve));
rl.close();
return passwordHash.generate(password);
}
function setUser(username, password) {
let file = getFile();
2020-04-26 20:12:50 +02:00
file[username] = password;
fs.writeFileSync("users.json", JSON.stringify(file));
2020-04-28 22:31:57 +02:00
console.log("User " + username + " created");
}
async function addUser() {
setUser(await getUsername(), await getPassword());
}
function delUser(username) {
let file = JSON.parse(fs.readFileSync("users.json"));
if (username in file) {
delete file[username];
fs.writeFileSync("users.json", JSON.stringify(file));
console.log("User " + username + " deleted");
return 0;
} else {
console.error("Username not found !");
return 1;
}
2020-04-26 20:12:50 +02:00
}
function isAuth(req, res, next) {
if (req.session.login) {
next();
} else {
2020-04-28 16:51:43 +02:00
res.redirect("/login?path=" + req.originalUrl);
2020-04-26 20:12:50 +02:00
}
}
2020-04-28 22:31:57 +02:00
module.exports = {
getFile: getFile,
getUsername: getUsername,
getPassword: getPassword,
setUser: setUser,
addUser: addUser,
delUser: delUser,
isAuth: isAuth
};
2020-04-26 20:12:50 +02:00