This commit is contained in:
nadja
2026-11-01 20:14:25 +01:00
parent 828c38c779
commit c4685c2152
1686 changed files with 570761 additions and 560 deletions

70
backend/server.ts Normal file
View File

@@ -0,0 +1,70 @@
import express, { Request, Response, NextFunction } from 'express';
import cors from 'cors';
import bcrypt from 'bcryptjs';
import jwt from 'jsonwebtoken';
import recipesRouter from './routes/recipes.js';
import authRouter from './routes/auth.js';
import analyticsRouter from './routes/analytics.js';
import { getUserByUsername, createUser } from './db.js';
import { trackEvent } from './analytics-db.js';
import { authMiddleware, adminMiddleware, AuthenticatedRequest } from './middleware.js';
const app = express();
const PORT = process.env.PORT || 3001;
const JWT_SECRET = process.env.JWT_SECRET || 'tiktok-rezepte-secret-key-change-in-production';
app.use(cors());
app.use(express.json());
app.use((req: Request, res: Response, next: NextFunction) => {
if (req.method === 'OPTIONS' || !req.path.startsWith('/api/')) return next();
if (req.path.startsWith('/api/analytics')) return next();
try {
let userId = null;
const authHeader = req.headers.authorization;
if (authHeader && authHeader.startsWith('Bearer ')) {
try {
const decoded = jwt.verify(authHeader.split(' ')[1], JWT_SECRET) as { username: string };
const user = getUserByUsername(decoded.username);
if (user) userId = user.id;
} catch {}
}
trackEvent('page_view', userId, { path: req.path, method: req.method });
} catch {}
next();
});
app.use('/api/auth', authRouter);
app.use('/api/recipes', recipesRouter);
app.use('/api/analytics', authMiddleware, adminMiddleware, analyticsRouter);
app.use((err: any, req: Request, res: Response, next: NextFunction) => {
console.error('Server Fehler:', err.message);
if (!res.headersSent) {
res.status(500).json({ error: 'Interner Serverfehler' });
}
});
process.on('uncaughtException', (err) => {
console.error('Uncaught Exception:', err.message);
});
process.on('unhandledRejection', (err: any) => {
console.error('Unhandled Rejection:', err?.message || err);
});
const adminUser = process.env.ADMIN_USER || 'admin';
const adminPass = process.env.ADMIN_PASS || 'admin123';
const existing = getUserByUsername(adminUser);
if (!existing) {
const hashed = bcrypt.hashSync(adminPass, 10);
createUser(adminUser, hashed, true);
console.log(`Admin erstellt: ${adminUser} / ${adminPass}`);
console.log('WICHTIG: Passwort nach dem ersten Login ändern!');
}
app.listen(Number(PORT), () => {
console.log(`Backend läuft auf http://localhost:${PORT}`);
});