@opengis/fastify-table
Version:
core-plugins
47 lines (46 loc) • 2.06 kB
JavaScript
import path from "node:path";
import { existsSync, readFileSync } from "node:fs";
import { createHash } from "node:crypto";
import config from "../../../../config.js";
import users from "./users.js";
import authorizeUser from "./authorizeUser.js";
export default async function loginFile(req, reply) {
const { username, password } = req.method === "POST" ? req.body : req.query;
const filepath = path.join(process.cwd(), "passwd");
if (!users?.length) {
const fileExists = existsSync(filepath);
if (!fileExists) {
req.log.error(req, "passwd file not exists");
return { error: "login error", status: 500 };
}
// parse file on start up
const data = readFileSync(filepath, "utf8");
const separator = data.indexOf("\\r\\n") !== -1 ? "\r\n" : "\n";
const rows = data.split(separator).map((row) => {
const [name, passwd, usertype = "regular", uid] = row.split(":");
return { username: name, password: passwd, usertype, uid };
});
rows.forEach((row) => users.push(row));
}
// check user / password
const user = users.find((el) => el.username === username);
const hashPasswd = createHash("sha1")
.update(`${password}${user?.salt || ""}`)
.digest("hex");
if (!user?.password || user.password !== hashPasswd) {
const txt = "Invalid user or password";
return req.method === "GET"
? reply.status(302).redirect(`/login?confirm=wrong_pass&message=${txt}`)
: reply.status(400).send({ message: txt });
}
const resultUser = {
uid: user?.uid || config?.auth?.uid || username,
user_name: username,
user_type: user.usertype || "regular",
};
const authType = "creds-" + (user.usertype === "admin" ? "admin" : "user");
const href = await authorizeUser(resultUser, req, authType); // creds-admin / creds-admin
return req.method === "GET"
? reply.status(302).redirect(href)
: reply.status(200).send(href);
}