Software: Apache. PHP/8.1.30 uname -a: Linux server1.tuhinhossain.com 5.15.0-163-generic #173-Ubuntu SMP Tue Oct 14 17:51:00 UTC uid=1002(picotech) gid=1003(picotech) groups=1003(picotech),0(root) Safe-mode: OFF (not secure) /home/picotech/domains/rentals.picotech.app/public_html/server/ drwxr-xr-x | |
| Viewing file: Select action/file-type: import express from 'express';
import cors from 'cors';
import path from 'path';
import { fileURLToPath } from 'url';
import dotenv from 'dotenv';
import bcrypt from 'bcryptjs';
import './jobs/cronJobs.js'
dotenv.config();
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
import { sequelize, User } from './models/index.js';
// Import routes
import authRoutes from './routes/auth.js';
import userRoutes from './routes/users.js';
import buildingRoutes from './routes/buildings.js';
import uploadRoutes from './routes/upload.js';
import floorRoutes from './routes/floor.js';
import roomRoutes from './routes/room.js';
import bedRoutes from './routes/bed.js';
import renterRoutes from './routes/renter.js';
import rentPaymentRoutes from './routes/rent.js';
import maintenanceRoutes from './routes/maintenance.js';
import expenseRoutes from './routes/expense.js';
import noticeRoutes from './routes/notice.js';
import visitorRoutes from './routes/visitor.js';
import settingsRoutes from './routes/settings.js';
import categoryRoutes from './routes/category.js';
import requestRoutes from './routes/request.js';
const app = express();
// Import security middleware
import { securityHeaders, sanitizeRequest, xssProtection, requestSizeLimiter } from './middleware/security.js';
import { apiLimiter } from './middleware/rateLimiter.js';
import { stripHtmlMiddleware } from './utils/htmlStrip.js';
import cookieParser from 'cookie-parser';
import { csrfProtection, addCsrfToken, csrfErrorHandler } from './middleware/csrf.js';
// Security middleware - Apply first
app.use(securityHeaders); // Helmet security headers
app.use(xssProtection); // Additional XSS protection
app.use(requestSizeLimiter); // Request size limiting
// Cookie parser (required for CSRF)
app.use(cookieParser());
// CORS configuration with whitelist
const allowedOrigins = process.env.ALLOWED_ORIGINS
? process.env.ALLOWED_ORIGINS.split(',')
: ['http://localhost:5173', 'http://localhost:3000'];
app.use(cors({
origin: (origin, callback) => {
// Allow requests with no origin (like mobile apps or curl requests)
if (!origin) return callback(null, true);
console.log("Oringin:", origin);
if (allowedOrigins.indexOf(origin) === -1) {
const msg = 'The CORS policy for this site does not allow access from the specified Origin.';
return callback(new Error(msg), false);
}
return callback(null, true);
},
credentials: true,
methods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH'],
allowedHeaders: ['Content-Type', 'Authorization', 'X-CSRF-Token']
}));
// Body parsing middleware with size limits
app.use((req, res, next) => {
const contentType = req.headers['content-type'] || '';
if (!contentType.includes('multipart/form-data')) {
express.json({ limit: '10mb' })(req, res, (err) => {
if (err) return next(err);
express.urlencoded({ extended: true, limit: '10mb' })(req, res, next);
});
} else {
next(); // Let multer handle multipart
}
});
// Strip HTML tags from all inputs
app.use(stripHtmlMiddleware);
// Request sanitization - Prevent NoSQL injection and XSS
app.use(sanitizeRequest);
// Apply rate limiting to all API routes
app.use('/api', apiLimiter);
// Serve static files
app.use('/uploads', express.static(path.join(__dirname, '../uploads')));
// CSRF token endpoint (no CSRF protection on this route)
app.get('/api/csrf-token', csrfProtection, (req, res) => {
res.json({ csrfToken: req.csrfToken() });
});
// Routes
import { authLimiter } from './middleware/rateLimiter.js';
// Apply CSRF protection to state-changing routes
app.use('/api/auth', authLimiter, authRoutes);
app.use('/api/users', csrfProtection, userRoutes);
app.use('/api/buildings', csrfProtection, buildingRoutes);
app.use('/api/upload', csrfProtection, uploadRoutes);
app.use('/api/floors', csrfProtection, floorRoutes);
app.use('/api/rooms', csrfProtection, roomRoutes);
app.use('/api/beds', csrfProtection, bedRoutes);
app.use('/api/renters', csrfProtection, renterRoutes);
app.use('/api/rents', csrfProtection, rentPaymentRoutes);
app.use('/api/maintenance', csrfProtection, maintenanceRoutes);
app.use('/api/expense', csrfProtection, expenseRoutes);
app.use('/api/notices', csrfProtection, noticeRoutes);
app.use('/api/visitors', csrfProtection, visitorRoutes);
app.use('/api/settings', csrfProtection, settingsRoutes);
app.use('/api/category', csrfProtection, categoryRoutes);
app.use('/api/request', csrfProtection, requestRoutes);
// Health check
app.get('/api/health', (req, res) => {
res.json({ status: 'OK', timestamp: new Date().toISOString() });
});
// CSRF error handling middleware
app.use(csrfErrorHandler);
// Error handling middleware
app.use((error, req, res, next) => {
console.error('Error:', error);
res.status(error.status || 500).json({
message: error.message || 'Internal server error',
...(process.env.NODE_ENV === 'development' && { stack: error.stack })
});
});
// 404 handler
// app.use('*', (req, res) => {
// res.status(404).json({ message: 'Route not found' });
// });
app.use('/assets', express.static(path.join(__dirname, '../dist/assets')));
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, '../dist/index.html')); // Adjust path as needed
});
const PORT = process.env.PORT || 3001;
// Database connection and server start
// await sequelize.sync({ alter: true })
const startServer = async () => {
try {
// Test database connection
await sequelize.authenticate();
console.log('Database connection established successfully.');
console.log('Database synchronized successfully.');
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
console.log(`Environment: ${process.env.NODE_ENV}`);
console.log(`API available at: http://localhost:${PORT}/api`);
});
} catch (error) {
console.error('Unable to start server:', error);
process.exit(1);
}
};
startServer(); |
:: Command execute :: | |
--[ c99shell v. 2.5 [PHP 8 Update] [24.05.2025] | Generation time: 0.0042 ]-- |