66 lines
1.8 KiB
JavaScript
Executable File
66 lines
1.8 KiB
JavaScript
Executable File
const express = require('express');
|
|
const path = require('path');
|
|
const { readSession, requireAuth } = require('./auth');
|
|
const { initDb } = require('./db');
|
|
|
|
const app = express();
|
|
const PORT = process.env.PORT || 3000;
|
|
|
|
app.use(express.json());
|
|
app.get('/health', (req, res) => {
|
|
res.json({ status: 'ok' });
|
|
});
|
|
|
|
async function start() {
|
|
await initDb();
|
|
|
|
app.use('/api/auth', require('./routes/auth'));
|
|
app.use('/api/records', requireAuth, require('./routes/records'));
|
|
app.use('/api/categories', requireAuth, require('./routes/categories'));
|
|
app.use('/api/statistics', requireAuth, require('./routes/statistics'));
|
|
app.use('/api/balance', requireAuth, require('./routes/balance'));
|
|
app.use('/api/users', requireAuth, require('./routes/users'));
|
|
|
|
const clientDist = path.join(__dirname, '..', 'client', 'dist');
|
|
const clientIndex = path.join(clientDist, 'index.html');
|
|
|
|
app.use(express.static(clientDist, { index: false }));
|
|
app.get('*', (req, res) => {
|
|
if (req.path.startsWith('/api')) {
|
|
return res.status(404).json({ error: 'API not found' });
|
|
}
|
|
|
|
const isAuthenticated = Boolean(readSession(req));
|
|
|
|
if (req.path === '/login') {
|
|
if (isAuthenticated) {
|
|
return res.redirect('/');
|
|
}
|
|
|
|
return res.sendFile(clientIndex);
|
|
}
|
|
|
|
if (!isAuthenticated) {
|
|
return res.redirect(`/login?redirect=${encodeURIComponent(req.originalUrl)}`);
|
|
}
|
|
|
|
return res.sendFile(clientIndex);
|
|
});
|
|
|
|
app.use((err, req, res, next) => {
|
|
console.error('Server error:', err.message);
|
|
res.status(err.status || 500).json({
|
|
error: err.message || 'Server internal error',
|
|
});
|
|
});
|
|
|
|
app.listen(PORT, () => {
|
|
console.log(`Accounting app listening on http://localhost:${PORT}`);
|
|
});
|
|
}
|
|
|
|
start().catch((error) => {
|
|
console.error('Failed to start server:', error);
|
|
process.exitCode = 1;
|
|
});
|