Initial commit — Умный Байт landing
This commit is contained in:
@@ -0,0 +1,34 @@
|
||||
{
|
||||
"name": "umbyte-backend",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "tsx watch src/index.ts",
|
||||
"build": "tsc",
|
||||
"start": "node dist/index.js",
|
||||
"migrate": "tsx src/db/migrate.ts",
|
||||
"create-admin": "tsx src/scripts/create-admin.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"bcrypt": "^5.1.1",
|
||||
"cookie-parser": "^1.4.7",
|
||||
"cors": "^2.8.5",
|
||||
"dotenv": "^16.4.5",
|
||||
"express": "^4.21.1",
|
||||
"jsonwebtoken": "^9.0.2",
|
||||
"pg": "^8.13.1",
|
||||
"zod": "^3.23.8"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/bcrypt": "^5.0.2",
|
||||
"@types/cookie-parser": "^1.4.7",
|
||||
"@types/cors": "^2.8.17",
|
||||
"@types/express": "^5.0.0",
|
||||
"@types/jsonwebtoken": "^9.0.7",
|
||||
"@types/node": "^22.9.0",
|
||||
"@types/pg": "^8.11.10",
|
||||
"tsx": "^4.19.2",
|
||||
"typescript": "^5.6.3"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
import jwt from 'jsonwebtoken';
|
||||
import bcrypt from 'bcrypt';
|
||||
import type { Request, Response, NextFunction } from 'express';
|
||||
|
||||
const JWT_SECRET = process.env.JWT_SECRET || 'change-me-please';
|
||||
const COOKIE_NAME = 'umbyte_session';
|
||||
const TOKEN_TTL_SEC = 60 * 60 * 24 * 7;
|
||||
|
||||
export interface AdminPayload {
|
||||
id: number;
|
||||
login: string;
|
||||
}
|
||||
|
||||
declare global {
|
||||
namespace Express {
|
||||
interface Request {
|
||||
admin?: AdminPayload;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function signToken(payload: AdminPayload): string {
|
||||
return jwt.sign(payload, JWT_SECRET, { expiresIn: TOKEN_TTL_SEC });
|
||||
}
|
||||
|
||||
export function setAuthCookie(res: Response, token: string): void {
|
||||
res.cookie(COOKIE_NAME, token, {
|
||||
httpOnly: true,
|
||||
secure: process.env.NODE_ENV === 'production',
|
||||
sameSite: 'lax',
|
||||
maxAge: TOKEN_TTL_SEC * 1000,
|
||||
path: '/',
|
||||
});
|
||||
}
|
||||
|
||||
export function clearAuthCookie(res: Response): void {
|
||||
res.clearCookie(COOKIE_NAME, { path: '/' });
|
||||
}
|
||||
|
||||
export function requireAdmin(
|
||||
req: Request,
|
||||
res: Response,
|
||||
next: NextFunction
|
||||
): void {
|
||||
const token = req.cookies?.[COOKIE_NAME];
|
||||
if (!token) {
|
||||
res.status(401).json({ error: 'unauthorized' });
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const payload = jwt.verify(token, JWT_SECRET) as AdminPayload;
|
||||
req.admin = payload;
|
||||
next();
|
||||
} catch {
|
||||
res.status(401).json({ error: 'unauthorized' });
|
||||
}
|
||||
}
|
||||
|
||||
export async function hashPassword(plain: string): Promise<string> {
|
||||
return bcrypt.hash(plain, 12);
|
||||
}
|
||||
|
||||
export async function verifyPassword(
|
||||
plain: string,
|
||||
hash: string
|
||||
): Promise<boolean> {
|
||||
return bcrypt.compare(plain, hash);
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { pool } from './pool.js';
|
||||
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = path.dirname(__filename);
|
||||
|
||||
const MIGRATIONS_DIR = path.resolve(__dirname, '../../../db');
|
||||
|
||||
export async function runMigrations(): Promise<void> {
|
||||
console.log('[migrate] Запуск миграций из', MIGRATIONS_DIR);
|
||||
|
||||
if (!fs.existsSync(MIGRATIONS_DIR)) {
|
||||
console.warn('[migrate] Папка миграций не найдена, пропускаю');
|
||||
return;
|
||||
}
|
||||
|
||||
const files = fs
|
||||
.readdirSync(MIGRATIONS_DIR)
|
||||
.filter((f) => f.endsWith('.sql'))
|
||||
.sort();
|
||||
|
||||
for (const file of files) {
|
||||
const fullPath = path.join(MIGRATIONS_DIR, file);
|
||||
const sql = fs.readFileSync(fullPath, 'utf-8');
|
||||
console.log(`[migrate] → ${file}`);
|
||||
try {
|
||||
await pool.query(sql);
|
||||
} catch (err) {
|
||||
console.error(`[migrate] Ошибка в ${file}:`, err);
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
console.log('[migrate] Все миграции применены');
|
||||
}
|
||||
|
||||
if (import.meta.url === `file://${process.argv[1]}`) {
|
||||
runMigrations()
|
||||
.then(() => process.exit(0))
|
||||
.catch((err) => {
|
||||
console.error(err);
|
||||
process.exit(1);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
import pg from 'pg';
|
||||
import dotenv from 'dotenv';
|
||||
|
||||
dotenv.config();
|
||||
|
||||
const { Pool } = pg;
|
||||
|
||||
export const pool = new Pool({
|
||||
host: process.env.DB_HOST || 'localhost',
|
||||
port: parseInt(process.env.DB_PORT || '5432', 10),
|
||||
user: process.env.DB_USER || 'umbyte',
|
||||
password: process.env.DB_PASSWORD || 'umbyte_dev_password',
|
||||
database: process.env.DB_NAME || 'umbyte',
|
||||
max: 10,
|
||||
idleTimeoutMillis: 30000,
|
||||
connectionTimeoutMillis: 5000,
|
||||
});
|
||||
|
||||
pool.on('error', (err) => {
|
||||
console.error('Unexpected PostgreSQL error', err);
|
||||
});
|
||||
|
||||
export async function query<T = unknown>(
|
||||
text: string,
|
||||
params?: unknown[]
|
||||
): Promise<T[]> {
|
||||
const result = await pool.query(text, params);
|
||||
return result.rows as T[];
|
||||
}
|
||||
|
||||
export async function queryOne<T = unknown>(
|
||||
text: string,
|
||||
params?: unknown[]
|
||||
): Promise<T | null> {
|
||||
const rows = await query<T>(text, params);
|
||||
return rows[0] ?? null;
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
import express from 'express';
|
||||
import cors from 'cors';
|
||||
import cookieParser from 'cookie-parser';
|
||||
import dotenv from 'dotenv';
|
||||
import { publicRouter } from './routes/public.js';
|
||||
import { adminRouter } from './routes/admin.js';
|
||||
import { runMigrations } from './db/migrate.js';
|
||||
import { initFirstAdmin } from './scripts/init-admin.js';
|
||||
|
||||
dotenv.config();
|
||||
|
||||
const app = express();
|
||||
const PORT = parseInt(process.env.PORT || '3000', 10);
|
||||
|
||||
app.use(express.json({ limit: '1mb' }));
|
||||
app.use(cookieParser());
|
||||
|
||||
app.use(
|
||||
cors({
|
||||
origin:
|
||||
process.env.NODE_ENV === 'production'
|
||||
? false
|
||||
: ['http://localhost:5173', 'http://127.0.0.1:5173'],
|
||||
credentials: true,
|
||||
})
|
||||
);
|
||||
|
||||
app.get('/api/health', (_req, res) => {
|
||||
res.json({ ok: true, service: 'umbyte-backend' });
|
||||
});
|
||||
|
||||
app.use('/api', publicRouter);
|
||||
app.use('/api/admin', adminRouter);
|
||||
|
||||
app.use((err: Error, _req: express.Request, res: express.Response, _next: express.NextFunction) => {
|
||||
console.error('[error]', err);
|
||||
res.status(500).json({ error: 'internal_error' });
|
||||
});
|
||||
|
||||
async function start() {
|
||||
try {
|
||||
await runMigrations();
|
||||
await initFirstAdmin();
|
||||
|
||||
app.listen(PORT, () => {
|
||||
console.log(`[umbyte-backend] listening on :${PORT}`);
|
||||
});
|
||||
} catch (err) {
|
||||
console.error('[startup] fatal error:', err);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
start();
|
||||
@@ -0,0 +1,233 @@
|
||||
import { Router } from 'express';
|
||||
import { z } from 'zod';
|
||||
import { query, queryOne } from '../db/pool.js';
|
||||
import {
|
||||
signToken,
|
||||
setAuthCookie,
|
||||
clearAuthCookie,
|
||||
requireAdmin,
|
||||
verifyPassword,
|
||||
} from '../auth/jwt.js';
|
||||
|
||||
export const adminRouter = Router();
|
||||
|
||||
const loginSchema = z.object({
|
||||
login: z.string().min(1).max(64),
|
||||
password: z.string().min(1).max(256),
|
||||
});
|
||||
|
||||
adminRouter.post('/login', async (req, res) => {
|
||||
const parsed = loginSchema.safeParse(req.body);
|
||||
if (!parsed.success) {
|
||||
res.status(400).json({ error: 'invalid_payload' });
|
||||
return;
|
||||
}
|
||||
|
||||
const { login, password } = parsed.data;
|
||||
|
||||
try {
|
||||
const user = await queryOne<{
|
||||
id: number;
|
||||
login: string;
|
||||
password_hash: string;
|
||||
}>(
|
||||
`SELECT id, login, password_hash FROM admin_users WHERE login = $1`,
|
||||
[login]
|
||||
);
|
||||
|
||||
if (!user) {
|
||||
res.status(401).json({ error: 'invalid_credentials' });
|
||||
return;
|
||||
}
|
||||
|
||||
const ok = await verifyPassword(password, user.password_hash);
|
||||
if (!ok) {
|
||||
res.status(401).json({ error: 'invalid_credentials' });
|
||||
return;
|
||||
}
|
||||
|
||||
await query(
|
||||
`UPDATE admin_users SET last_login = now() WHERE id = $1`,
|
||||
[user.id]
|
||||
);
|
||||
|
||||
const token = signToken({ id: user.id, login: user.login });
|
||||
setAuthCookie(res, token);
|
||||
res.json({ ok: true, login: user.login });
|
||||
} catch (err) {
|
||||
console.error('[POST /admin/login]', err);
|
||||
res.status(500).json({ error: 'internal_error' });
|
||||
}
|
||||
});
|
||||
|
||||
adminRouter.post('/logout', (_req, res) => {
|
||||
clearAuthCookie(res);
|
||||
res.json({ ok: true });
|
||||
});
|
||||
|
||||
adminRouter.get('/me', requireAdmin, (req, res) => {
|
||||
res.json({ admin: req.admin });
|
||||
});
|
||||
|
||||
const productSchema = z.object({
|
||||
slug: z.string().min(1).max(64),
|
||||
title: z.string().min(1).max(128),
|
||||
subtitle: z.string().max(256).nullable().optional(),
|
||||
description: z.string().min(1),
|
||||
status: z.enum(['production', 'development', 'planned']),
|
||||
audience: z.enum(['B2B', 'B2C', 'global']).nullable().optional(),
|
||||
icon_key: z.string().max(64).nullable().optional(),
|
||||
tags: z.array(z.string()),
|
||||
is_published: z.boolean().optional(),
|
||||
sort_order: z.number().int().optional(),
|
||||
});
|
||||
|
||||
adminRouter.get('/products', requireAdmin, async (_req, res) => {
|
||||
const products = await query(
|
||||
`SELECT * FROM products ORDER BY sort_order ASC`
|
||||
);
|
||||
res.json({ products });
|
||||
});
|
||||
|
||||
adminRouter.post('/products', requireAdmin, async (req, res) => {
|
||||
const parsed = productSchema.safeParse(req.body);
|
||||
if (!parsed.success) {
|
||||
res.status(400).json({ error: 'invalid_payload' });
|
||||
return;
|
||||
}
|
||||
const p = parsed.data;
|
||||
const created = await queryOne(
|
||||
`INSERT INTO products (slug, title, subtitle, description, status,
|
||||
audience, icon_key, tags, is_published, sort_order)
|
||||
VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10)
|
||||
RETURNING *`,
|
||||
[
|
||||
p.slug, p.title, p.subtitle ?? null, p.description, p.status,
|
||||
p.audience ?? null, p.icon_key ?? null, JSON.stringify(p.tags),
|
||||
p.is_published ?? true, p.sort_order ?? 0,
|
||||
]
|
||||
);
|
||||
res.status(201).json({ product: created });
|
||||
});
|
||||
|
||||
adminRouter.put('/products/:id', requireAdmin, async (req, res) => {
|
||||
const id = parseInt(req.params.id, 10);
|
||||
if (Number.isNaN(id)) {
|
||||
res.status(400).json({ error: 'invalid_id' });
|
||||
return;
|
||||
}
|
||||
const parsed = productSchema.partial().safeParse(req.body);
|
||||
if (!parsed.success) {
|
||||
res.status(400).json({ error: 'invalid_payload' });
|
||||
return;
|
||||
}
|
||||
const p = parsed.data;
|
||||
const updated = await queryOne(
|
||||
`UPDATE products SET
|
||||
slug = COALESCE($2, slug),
|
||||
title = COALESCE($3, title),
|
||||
subtitle = COALESCE($4, subtitle),
|
||||
description = COALESCE($5, description),
|
||||
status = COALESCE($6, status),
|
||||
audience = COALESCE($7, audience),
|
||||
icon_key = COALESCE($8, icon_key),
|
||||
tags = COALESCE($9, tags),
|
||||
is_published = COALESCE($10, is_published),
|
||||
sort_order = COALESCE($11, sort_order),
|
||||
updated_at = now()
|
||||
WHERE id = $1
|
||||
RETURNING *`,
|
||||
[
|
||||
id, p.slug, p.title, p.subtitle, p.description, p.status,
|
||||
p.audience, p.icon_key,
|
||||
p.tags ? JSON.stringify(p.tags) : null,
|
||||
p.is_published, p.sort_order,
|
||||
]
|
||||
);
|
||||
if (!updated) {
|
||||
res.status(404).json({ error: 'not_found' });
|
||||
return;
|
||||
}
|
||||
res.json({ product: updated });
|
||||
});
|
||||
|
||||
adminRouter.delete('/products/:id', requireAdmin, async (req, res) => {
|
||||
const id = parseInt(req.params.id, 10);
|
||||
await query(`DELETE FROM products WHERE id = $1`, [id]);
|
||||
res.json({ ok: true });
|
||||
});
|
||||
|
||||
adminRouter.get('/sections', requireAdmin, async (_req, res) => {
|
||||
const sections = await query(
|
||||
`SELECT * FROM sections ORDER BY sort_order ASC`
|
||||
);
|
||||
res.json({ sections });
|
||||
});
|
||||
|
||||
adminRouter.put('/sections/:key', requireAdmin, async (req, res) => {
|
||||
const { key } = req.params;
|
||||
const { content_json, title, is_active } = req.body;
|
||||
const updated = await queryOne(
|
||||
`UPDATE sections SET
|
||||
content_json = COALESCE($2, content_json),
|
||||
title = COALESCE($3, title),
|
||||
is_active = COALESCE($4, is_active),
|
||||
updated_at = now()
|
||||
WHERE key = $1
|
||||
RETURNING *`,
|
||||
[key, content_json ?? null, title ?? null, is_active ?? null]
|
||||
);
|
||||
if (!updated) {
|
||||
res.status(404).json({ error: 'not_found' });
|
||||
return;
|
||||
}
|
||||
res.json({ section: updated });
|
||||
});
|
||||
|
||||
adminRouter.get('/approach', requireAdmin, async (_req, res) => {
|
||||
const items = await query(
|
||||
`SELECT * FROM approach_items ORDER BY sort_order ASC`
|
||||
);
|
||||
res.json({ items });
|
||||
});
|
||||
|
||||
adminRouter.put('/approach/:id', requireAdmin, async (req, res) => {
|
||||
const id = parseInt(req.params.id, 10);
|
||||
const { title, description, icon_key, sort_order, is_active } = req.body;
|
||||
const updated = await queryOne(
|
||||
`UPDATE approach_items SET
|
||||
title = COALESCE($2, title),
|
||||
description = COALESCE($3, description),
|
||||
icon_key = COALESCE($4, icon_key),
|
||||
sort_order = COALESCE($5, sort_order),
|
||||
is_active = COALESCE($6, is_active)
|
||||
WHERE id = $1
|
||||
RETURNING *`,
|
||||
[id, title, description, icon_key, sort_order, is_active]
|
||||
);
|
||||
res.json({ item: updated });
|
||||
});
|
||||
|
||||
adminRouter.get('/settings', requireAdmin, async (_req, res) => {
|
||||
const rows = await query<{ key: string; value: string }>(
|
||||
`SELECT key, value FROM settings`
|
||||
);
|
||||
const settings: Record<string, string> = {};
|
||||
for (const r of rows) settings[r.key] = r.value;
|
||||
res.json({ settings });
|
||||
});
|
||||
|
||||
adminRouter.put('/settings/:key', requireAdmin, async (req, res) => {
|
||||
const { key } = req.params;
|
||||
const { value } = req.body;
|
||||
if (typeof value !== 'string') {
|
||||
res.status(400).json({ error: 'invalid_payload' });
|
||||
return;
|
||||
}
|
||||
await query(
|
||||
`INSERT INTO settings (key, value) VALUES ($1, $2)
|
||||
ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value, updated_at = now()`,
|
||||
[key, value]
|
||||
);
|
||||
res.json({ ok: true });
|
||||
});
|
||||
@@ -0,0 +1,53 @@
|
||||
import { Router } from 'express';
|
||||
import { query } from '../db/pool.js';
|
||||
|
||||
export const publicRouter = Router();
|
||||
|
||||
publicRouter.get('/content', async (_req, res) => {
|
||||
try {
|
||||
const [sections, products, approach, settings] = await Promise.all([
|
||||
query<{ key: string; title: string; content_json: unknown; sort_order: number }>(
|
||||
`SELECT key, title, content_json, sort_order
|
||||
FROM sections
|
||||
WHERE is_active = true
|
||||
ORDER BY sort_order ASC`
|
||||
),
|
||||
query<unknown>(
|
||||
`SELECT id, slug, title, subtitle, description,
|
||||
status, audience, icon_key, tags, sort_order
|
||||
FROM products
|
||||
WHERE is_published = true
|
||||
ORDER BY sort_order ASC`
|
||||
),
|
||||
query<unknown>(
|
||||
`SELECT id, title, description, icon_key, sort_order
|
||||
FROM approach_items
|
||||
WHERE is_active = true
|
||||
ORDER BY sort_order ASC`
|
||||
),
|
||||
query<{ key: string; value: string }>(
|
||||
`SELECT key, value FROM settings`
|
||||
),
|
||||
]);
|
||||
|
||||
const sectionsMap: Record<string, unknown> = {};
|
||||
for (const s of sections) {
|
||||
sectionsMap[s.key] = s.content_json;
|
||||
}
|
||||
|
||||
const settingsMap: Record<string, string> = {};
|
||||
for (const s of settings) {
|
||||
settingsMap[s.key] = s.value;
|
||||
}
|
||||
|
||||
res.json({
|
||||
sections: sectionsMap,
|
||||
products,
|
||||
approach,
|
||||
settings: settingsMap,
|
||||
});
|
||||
} catch (err) {
|
||||
console.error('[GET /content]', err);
|
||||
res.status(500).json({ error: 'internal_error' });
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,28 @@
|
||||
import { queryOne, query } from '../db/pool.js';
|
||||
import { hashPassword } from '../auth/jwt.js';
|
||||
|
||||
export async function initFirstAdmin(): Promise<void> {
|
||||
const existing = await queryOne<{ count: string }>(
|
||||
`SELECT COUNT(*)::text AS count FROM admin_users`
|
||||
);
|
||||
|
||||
const count = parseInt(existing?.count || '0', 10);
|
||||
if (count > 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const password = process.env.ADMIN_INITIAL_PASSWORD || 'admin';
|
||||
const hash = await hashPassword(password);
|
||||
|
||||
await query(
|
||||
`INSERT INTO admin_users (login, password_hash) VALUES ($1, $2)`,
|
||||
['admin', hash]
|
||||
);
|
||||
|
||||
console.log('[init-admin] Создан первый админ: admin');
|
||||
if (password === 'admin') {
|
||||
console.warn(
|
||||
'[init-admin] ВНИМАНИЕ: используется дефолтный пароль "admin". Смените его сразу!'
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "Bundler",
|
||||
"lib": ["ES2022"],
|
||||
"outDir": "./dist",
|
||||
"rootDir": "./src",
|
||||
"strict": true,
|
||||
"esModuleInterop": true,
|
||||
"skipLibCheck": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"resolveJsonModule": true,
|
||||
"allowImportingTsExtensions": false,
|
||||
"verbatimModuleSyntax": false
|
||||
},
|
||||
"include": ["src/**/*"],
|
||||
"exclude": ["node_modules", "dist"]
|
||||
}
|
||||
Reference in New Issue
Block a user