Files
2026-05-20 17:42:01 -06:00

37 lines
1.0 KiB
JavaScript

const fs = require("fs");
function login(filePath, username, password) {
const raw = fs.readFileSync(filePath, "utf8");
const state = JSON.parse(raw);
const user = state.users.find((item) => item.username === username);
if (!user) {
throw new Error("User not found");
}
if (user.lockedUntil && new Date(user.lockedUntil).getTime() > Date.now()) {
return { ok: false, reason: "locked" };
}
if (user.password !== password) {
user.failedAttempts = user.failedAttempts + 1;
if (user.failedAttempts >= 3) {
user.lockedUntil = new Date(Date.now() + 15 * 60 * 1000).toISOString();
}
fs.writeFileSync(filePath, JSON.stringify(state, null, 2));
return { ok: false, reason: "invalid-password" };
}
user.failedAttempts = 0;
user.lockedUntil = null;
user.lastLoginAt = new Date().toISOString();
fs.writeFileSync(filePath, JSON.stringify(state, null, 2));
console.log("Logged in", username);
return { ok: true, token: "token-" + username + "-" + Date.now() };
}
module.exports = { login };