mne-nuzhno-sozdat-sayt-dlya/server.js

148 lines
5.9 KiB
JavaScript

const http = require("http");
const fs = require("fs");
const path = require("path");
const PORT = process.env.PORT || 3000;
const DATA = path.join(__dirname, "data.json");
function readData() {
try { return JSON.parse(fs.readFileSync(DATA, "utf8")); } catch (_) { return { users: [], items: [], log: [] }; }
}
function writeData(d) {
fs.writeFileSync(DATA, JSON.stringify(d, null, 2));
}
function body(req) {
return new Promise((resolve) => {
let s = "";
req.on("data", (c) => (s += c));
req.on("end", () => { try { resolve(JSON.parse(s || "{}")); } catch (_) { resolve({}); } });
});
}
const sessions = new Map();
http.createServer(async (req, res) => {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
res.setHeader("Access-Control-Allow-Headers", "Content-Type");
if (req.method === "OPTIONS") {
res.writeHead(204);
return res.end();
}
const url = req.url.split("?")[0];
const cookie = req.headers.cookie || "";
const sessionId = cookie.split(";").find(c => c.trim().startsWith("session="))?.split("=")[1];
const user = sessionId ? sessions.get(sessionId) : null;
// API: вход
if (req.method === "POST" && url === "/api/login") {
const { login, password } = await body(req);
const data = readData();
const found = data.users.find(u => u.login === login && u.password === password);
if (found) {
const sid = Math.random().toString(36).slice(2);
sessions.set(sid, { id: found.id, login: found.login, name: found.name, role: found.role });
res.setHeader("Set-Cookie", `session=${sid}; Path=/; Max-Age=86400`);
res.writeHead(200, { "Content-Type": "application/json" });
return res.end(JSON.stringify({ ok: true, user: { id: found.id, login: found.login, name: found.name, role: found.role } }));
}
res.writeHead(401, { "Content-Type": "application/json" });
return res.end(JSON.stringify({ ok: false, error: "Неверный логин или пароль" }));
}
// API: выход
if (req.method === "POST" && url === "/api/logout") {
if (sessionId) sessions.delete(sessionId);
res.setHeader("Set-Cookie", "session=; Path=/; Max-Age=0");
res.writeHead(200, { "Content-Type": "application/json" });
return res.end(JSON.stringify({ ok: true }));
}
// API: текущий пользователь
if (req.method === "GET" && url === "/api/me") {
if (user) {
res.writeHead(200, { "Content-Type": "application/json" });
return res.end(JSON.stringify({ ok: true, user }));
}
res.writeHead(401, { "Content-Type": "application/json" });
return res.end(JSON.stringify({ ok: false }));
}
// API: получить все приказы (требуется вход)
if (req.method === "GET" && url === "/api/items") {
if (!user) {
res.writeHead(401, { "Content-Type": "application/json" });
return res.end(JSON.stringify({ error: "Требуется авторизация" }));
}
res.writeHead(200, { "Content-Type": "application/json" });
return res.end(JSON.stringify(readData()));
}
// API: добавить приказ (требуется вход)
if (req.method === "POST" && url === "/api/items") {
if (!user) {
res.writeHead(401, { "Content-Type": "application/json" });
return res.end(JSON.stringify({ error: "Требуется авторизация" }));
}
const item = await body(req);
const data = readData();
const newItem = { id: Date.now(), ...item };
data.items.push(newItem);
data.log.push({ when: new Date().toISOString(), what: "Добавлен приказ " + newItem.number, who: user.name });
writeData(data);
res.writeHead(200, { "Content-Type": "application/json" });
return res.end(JSON.stringify({ ok: true, item: newItem }));
}
// API: обновить приказ (требуется вход)
if (req.method === "PUT" && url === "/api/items") {
if (!user) {
res.writeHead(401, { "Content-Type": "application/json" });
return res.end(JSON.stringify({ error: "Требуется авторизация" }));
}
const item = await body(req);
const data = readData();
const idx = data.items.findIndex(i => i.id === item.id);
if (idx !== -1) {
data.items[idx] = { ...data.items[idx], ...item };
data.log.push({ when: new Date().toISOString(), what: "Обновлён приказ " + item.number, who: user.name });
writeData(data);
}
res.writeHead(200, { "Content-Type": "application/json" });
return res.end(JSON.stringify({ ok: true }));
}
// API: удалить приказ (требуется вход)
if (req.method === "DELETE" && url === "/api/items") {
if (!user) {
res.writeHead(401, { "Content-Type": "application/json" });
return res.end(JSON.stringify({ error: "Требуется авторизация" }));
}
const { id } = await body(req);
const data = readData();
const found = data.items.find(i => i.id === id);
data.items = data.items.filter(i => i.id !== id);
if (found) {
data.log.push({ when: new Date().toISOString(), what: "Удалён приказ " + found.number, who: user.name });
writeData(data);
}
res.writeHead(200, { "Content-Type": "application/json" });
return res.end(JSON.stringify({ ok: true }));
}
// Статика
let file = url === "/" ? "/index.html" : url;
const full = path.join(__dirname, file);
if (full.startsWith(__dirname) && fs.existsSync(full) && fs.statSync(full).isFile()) {
const ext = path.extname(full);
const type = ext === ".css" ? "text/css" : ext === ".js" ? "application/javascript" : "text/html";
res.writeHead(200, { "Content-Type": type + "; charset=utf-8" });
return res.end(fs.readFileSync(full));
}
res.writeHead(404);
res.end("Not found");
}).listen(PORT, () => console.log("Сервер запущен на порту " + PORT));