2025-11-10 17:09:35 +03:00
|
|
|
require('dotenv').config({ path: require('path').join(__dirname, '../.env') });
|
2025-11-10 17:00:40 +03:00
|
|
|
const express = require('express');
|
|
|
|
|
const session = require('express-session');
|
|
|
|
|
const helmet = require('helmet');
|
|
|
|
|
const cors = require('cors');
|
|
|
|
|
const logger = require('./config/logger');
|
|
|
|
|
const sessionConfig = require('./config/session');
|
|
|
|
|
const { testConnection } = require('./config/database');
|
|
|
|
|
const errorHandler = require('./middlewares/errorHandler');
|
|
|
|
|
const { apiLimiter } = require('./middlewares/rateLimiter');
|
|
|
|
|
|
|
|
|
|
const app = express();
|
|
|
|
|
const PORT = process.env.PORT || 3000;
|
|
|
|
|
|
|
|
|
|
// Security middleware
|
|
|
|
|
app.use(helmet());
|
2025-11-10 20:01:41 +03:00
|
|
|
|
|
|
|
|
// Dynamic CORS configuration (will be updated from settings)
|
|
|
|
|
let corsOptions = {
|
|
|
|
|
origin: process.env.FRONTEND_URL || 'http://localhost:5173',
|
2025-11-10 17:00:40 +03:00
|
|
|
credentials: true,
|
2025-11-10 20:01:41 +03:00
|
|
|
};
|
|
|
|
|
|
|
|
|
|
app.use((req, res, next) => {
|
|
|
|
|
cors(corsOptions)(req, res, next);
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
// Function to update CORS from database
|
|
|
|
|
const updateCorsFromSettings = async () => {
|
|
|
|
|
try {
|
|
|
|
|
const { Settings } = require('./models');
|
|
|
|
|
const corsEnabledSetting = await Settings.findOne({ where: { key: 'cors_enabled' } });
|
|
|
|
|
const frontendUrlSetting = await Settings.findOne({ where: { key: 'frontend_url' } });
|
|
|
|
|
|
|
|
|
|
if (corsEnabledSetting && corsEnabledSetting.value === 'true' && frontendUrlSetting) {
|
|
|
|
|
corsOptions.origin = frontendUrlSetting.value;
|
|
|
|
|
logger.info(`CORS enabled for: ${frontendUrlSetting.value}`);
|
|
|
|
|
} else {
|
|
|
|
|
// Default: allow both frontend and backend on same origin
|
|
|
|
|
corsOptions.origin = process.env.FRONTEND_URL || 'http://localhost:5173';
|
|
|
|
|
}
|
|
|
|
|
} catch (error) {
|
|
|
|
|
logger.warn('Could not load CORS settings from database, using defaults');
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
// Update CORS on startup (with delay to ensure DB is ready)
|
|
|
|
|
setTimeout(updateCorsFromSettings, 2000);
|
|
|
|
|
|
|
|
|
|
// Export for use in settings controller
|
|
|
|
|
app.updateCorsSettings = updateCorsFromSettings;
|
2025-11-10 17:00:40 +03:00
|
|
|
|
|
|
|
|
// Body parsing middleware
|
|
|
|
|
app.use(express.json());
|
|
|
|
|
app.use(express.urlencoded({ extended: true }));
|
|
|
|
|
|
|
|
|
|
// Serve static files (landing page)
|
|
|
|
|
app.use(express.static('src/public'));
|
|
|
|
|
|
|
|
|
|
// Session middleware
|
|
|
|
|
app.use(session(sessionConfig));
|
|
|
|
|
|
|
|
|
|
// Rate limiting
|
|
|
|
|
app.use('/api', apiLimiter);
|
|
|
|
|
|
|
|
|
|
// Request logging
|
|
|
|
|
app.use((req, res, next) => {
|
|
|
|
|
logger.info(`${req.method} ${req.path}`, {
|
|
|
|
|
ip: req.ip,
|
|
|
|
|
userAgent: req.get('user-agent'),
|
|
|
|
|
});
|
|
|
|
|
next();
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
// Health check
|
|
|
|
|
app.get('/health', (req, res) => {
|
|
|
|
|
res.json({
|
|
|
|
|
success: true,
|
|
|
|
|
message: 'Server is running',
|
|
|
|
|
timestamp: new Date().toISOString(),
|
|
|
|
|
});
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
// API Routes
|
|
|
|
|
app.use('/api/auth', require('./routes/auth.routes'));
|
|
|
|
|
app.use('/api/companies', require('./routes/company.routes'));
|
|
|
|
|
app.use('/api/tokens', require('./routes/token.routes'));
|
|
|
|
|
app.use('/api/templates', require('./routes/template.routes'));
|
|
|
|
|
app.use('/api/settings', require('./routes/settings.routes'));
|
|
|
|
|
app.use('/api/stats', require('./routes/stats.routes'));
|
|
|
|
|
|
|
|
|
|
// Public tracking route (no rate limit on this specific route)
|
|
|
|
|
app.use('/t', require('./routes/tracking.routes'));
|
|
|
|
|
|
|
|
|
|
// 404 handler
|
|
|
|
|
app.use((req, res) => {
|
|
|
|
|
res.status(404).json({
|
|
|
|
|
success: false,
|
|
|
|
|
error: 'Endpoint not found',
|
|
|
|
|
});
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
// Error handler (must be last)
|
|
|
|
|
app.use(errorHandler);
|
|
|
|
|
|
|
|
|
|
// Start server
|
|
|
|
|
const startServer = async () => {
|
|
|
|
|
try {
|
|
|
|
|
// Test database connection
|
|
|
|
|
await testConnection();
|
|
|
|
|
|
|
|
|
|
// Start listening
|
|
|
|
|
app.listen(PORT, () => {
|
|
|
|
|
logger.info(`🚀 Server is running on port ${PORT}`);
|
|
|
|
|
logger.info(`📊 Environment: ${process.env.NODE_ENV || 'development'}`);
|
|
|
|
|
logger.info(`🔗 Health check: http://localhost:${PORT}/health`);
|
|
|
|
|
console.log(`\n✨ Oltalama Backend Server Started!`);
|
|
|
|
|
console.log(`🌐 API: http://localhost:${PORT}/api`);
|
|
|
|
|
console.log(`🎯 Tracking: http://localhost:${PORT}/t/:token\n`);
|
|
|
|
|
});
|
|
|
|
|
} catch (error) {
|
|
|
|
|
logger.error('Failed to start server:', error);
|
|
|
|
|
process.exit(1);
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
startServer();
|
|
|
|
|
|
|
|
|
|
module.exports = app;
|
|
|
|
|
|