steelforesight/panel/server.js

166 lines
6.2 KiB
JavaScript

import 'dotenv/config';
import express from 'express';
import cors from 'cors';
import multer from 'multer';
import bcrypt from 'bcryptjs';
import jwt from 'jsonwebtoken';
import { nanoid } from 'nanoid';
import path from 'node:path';
import fs from 'node:fs';
import { fileURLToPath } from 'node:url';
import { db, rowToArticle } from './db.js';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const PORT = Number(process.env.PORT || 3001);
const JWT_SECRET = process.env.JWT_SECRET || 'change-me-in-production';
const PUBLIC_ORIGIN = process.env.PUBLIC_ORIGIN || `http://localhost:${PORT}`;
const uploadsDir = path.join(__dirname, 'uploads');
if (!fs.existsSync(uploadsDir)) fs.mkdirSync(uploadsDir, { recursive: true });
const storage = multer.diskStorage({
destination: (_req, _file, cb) => cb(null, uploadsDir),
filename: (_req, file, cb) => {
const ext = path.extname(file.originalname).toLowerCase().slice(0, 8) || '.bin';
cb(null, `${nanoid(12)}${ext}`);
},
});
const upload = multer({
storage,
limits: { fileSize: 10 * 1024 * 1024 },
fileFilter: (_req, file, cb) => {
if (/^image\/(jpe?g|png|webp|gif|svg\+xml)$/.test(file.mimetype)) cb(null, true);
else cb(new Error('Only image uploads are allowed'));
},
});
const app = express();
app.use(cors({ origin: true, credentials: true }));
app.use(express.json({ limit: '2mb' }));
app.use('/uploads', express.static(uploadsDir, { maxAge: '7d' }));
app.use('/', express.static(path.join(__dirname, 'public')));
function authRequired(req, res, next) {
const header = req.headers.authorization || '';
const token = header.startsWith('Bearer ') ? header.slice(7) : null;
if (!token) return res.status(401).json({ error: 'unauthorized' });
try {
req.user = jwt.verify(token, JWT_SECRET);
next();
} catch {
return res.status(401).json({ error: 'invalid_token' });
}
}
app.post('/api/auth/login', (req, res) => {
const { username, password } = req.body || {};
if (!username || !password) return res.status(400).json({ error: 'username_password_required' });
const row = db.prepare('SELECT id, username, password_hash FROM users WHERE username = ?').get(username);
if (!row) return res.status(401).json({ error: 'bad_credentials' });
if (!bcrypt.compareSync(password, row.password_hash)) {
return res.status(401).json({ error: 'bad_credentials' });
}
const token = jwt.sign({ sub: row.id, username: row.username }, JWT_SECRET, { expiresIn: '7d' });
res.json({ token, user: { id: row.id, username: row.username } });
});
app.get('/api/auth/me', authRequired, (req, res) => {
res.json({ user: req.user });
});
const PUBLIC_FIELDS = `
id, title, category, type, author, author_role, author_initial,
publish_date, pages, price, is_free, summary, body, cover_image,
tags, featured, created_at, updated_at
`;
app.get('/api/articles', (req, res) => {
const limit = Math.min(Number(req.query.limit) || 50, 200);
const rows = db
.prepare(`SELECT ${PUBLIC_FIELDS} FROM articles ORDER BY created_at DESC LIMIT ?`)
.all(limit);
res.json(rows.map(rowToArticle));
});
app.get('/api/articles/:id', (req, res) => {
const row = db.prepare(`SELECT ${PUBLIC_FIELDS} FROM articles WHERE id = ?`).get(req.params.id);
if (!row) return res.status(404).json({ error: 'not_found' });
res.json(rowToArticle(row));
});
app.post('/api/uploads', authRequired, upload.single('file'), (req, res) => {
if (!req.file) return res.status(400).json({ error: 'no_file' });
const relative = `/uploads/${req.file.filename}`;
res.json({ url: relative, absoluteUrl: `${PUBLIC_ORIGIN}${relative}` });
});
function normalizeArticleBody(b) {
return {
title: String(b.title || '').trim(),
category: b.category || null,
type: b.type || null,
author: b.author || null,
author_role: b.authorRole || null,
author_initial: b.authorInitial || null,
publish_date: b.publishDate || null,
pages: Number(b.pages) || 0,
price: Number(b.price) || 0,
is_free: b.isFree ? 1 : 0,
summary: b.summary || null,
body: b.body || null,
cover_image: b.coverImage || null,
tags: JSON.stringify(Array.isArray(b.tags) ? b.tags : []),
featured: b.featured ? 1 : 0,
};
}
app.post('/api/articles', authRequired, (req, res) => {
const a = normalizeArticleBody(req.body || {});
if (!a.title) return res.status(400).json({ error: 'title_required' });
const id = nanoid(14);
db.prepare(`
INSERT INTO articles (
id, title, category, type, author, author_role, author_initial,
publish_date, pages, price, is_free, summary, body, cover_image,
tags, featured
) VALUES (
@id, @title, @category, @type, @author, @author_role, @author_initial,
@publish_date, @pages, @price, @is_free, @summary, @body, @cover_image,
@tags, @featured
)
`).run({ id, ...a });
const row = db.prepare(`SELECT ${PUBLIC_FIELDS} FROM articles WHERE id = ?`).get(id);
res.status(201).json(rowToArticle(row));
});
app.put('/api/articles/:id', authRequired, (req, res) => {
const existing = db.prepare('SELECT id FROM articles WHERE id = ?').get(req.params.id);
if (!existing) return res.status(404).json({ error: 'not_found' });
const a = normalizeArticleBody(req.body || {});
if (!a.title) return res.status(400).json({ error: 'title_required' });
db.prepare(`
UPDATE articles SET
title = @title, category = @category, type = @type,
author = @author, author_role = @author_role, author_initial = @author_initial,
publish_date = @publish_date, pages = @pages, price = @price, is_free = @is_free,
summary = @summary, body = @body, cover_image = @cover_image,
tags = @tags, featured = @featured,
updated_at = datetime('now')
WHERE id = @id
`).run({ id: req.params.id, ...a });
const row = db.prepare(`SELECT ${PUBLIC_FIELDS} FROM articles WHERE id = ?`).get(req.params.id);
res.json(rowToArticle(row));
});
app.delete('/api/articles/:id', authRequired, (req, res) => {
const info = db.prepare('DELETE FROM articles WHERE id = ?').run(req.params.id);
if (info.changes === 0) return res.status(404).json({ error: 'not_found' });
res.status(204).end();
});
app.get('/api/health', (_req, res) => res.json({ ok: true }));
app.listen(PORT, () => {
console.log(`Panel running at ${PUBLIC_ORIGIN}`);
});