76 lines
1.8 KiB
TypeScript
76 lines
1.8 KiB
TypeScript
import express from 'express';
|
|
import session from 'express-session';
|
|
import cookieParser from 'cookie-parser';
|
|
import cors from 'cors';
|
|
import path from 'path';
|
|
import { fileURLToPath } from 'url';
|
|
|
|
import { initializeDatabase } from './database.js';
|
|
import authRoutes from './routes/auth.js';
|
|
import adminRoutes from './routes/admin.js';
|
|
import questionnaireRoutes from './routes/questionnaire.js';
|
|
|
|
const __filename = fileURLToPath(import.meta.url);
|
|
const __dirname = path.dirname(__filename);
|
|
|
|
// Initialize database
|
|
initializeDatabase();
|
|
|
|
const app = express();
|
|
const PORT = process.env.PORT || 4000;
|
|
const isProduction = process.env.NODE_ENV === 'production';
|
|
|
|
// Middleware
|
|
app.use(express.json());
|
|
app.use(express.urlencoded({ extended: true }));
|
|
app.use(cookieParser());
|
|
|
|
// CORS for development
|
|
if (!isProduction) {
|
|
app.use(cors({
|
|
origin: 'http://localhost:5173',
|
|
credentials: true,
|
|
}));
|
|
}
|
|
|
|
// Session configuration
|
|
declare module 'express-session' {
|
|
interface SessionData {
|
|
user?: { id: number; username: string };
|
|
returnTo?: string;
|
|
}
|
|
}
|
|
|
|
app.use(session({
|
|
secret: process.env.SESSION_SECRET || 'dev-secret-change-in-production',
|
|
resave: false,
|
|
saveUninitialized: false,
|
|
cookie: {
|
|
secure: isProduction && process.env.HTTPS === 'true',
|
|
httpOnly: true,
|
|
maxAge: 24 * 60 * 60 * 1000, // 24 hours
|
|
sameSite: isProduction ? 'strict' : 'lax',
|
|
},
|
|
}));
|
|
|
|
// API Routes
|
|
app.use('/api/auth', authRoutes);
|
|
app.use('/api/admin', adminRoutes);
|
|
app.use('/api/q', questionnaireRoutes);
|
|
|
|
// Serve static files in production
|
|
if (isProduction) {
|
|
const clientPath = path.join(__dirname, '../client');
|
|
app.use(express.static(clientPath));
|
|
|
|
// SPA fallback
|
|
app.get('*', (req, res) => {
|
|
res.sendFile(path.join(clientPath, 'index.html'));
|
|
});
|
|
}
|
|
|
|
app.listen(PORT, () => {
|
|
console.log(`Server running on http://localhost:${PORT}`);
|
|
});
|
|
|