-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
147 lines (131 loc) · 4.39 KB
/
app.js
File metadata and controls
147 lines (131 loc) · 4.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
const express = require('express');
const helmet = require('helmet');
const cors = require('cors');
const rateLimit = require('express-rate-limit');
const compression = require('compression');
const morgan = require('morgan');
const app = express();
const flash = require('connect-flash');
const session = require('express-session');
const PORT = process.env.PORT || 4000;
require('dotenv').config();
const homeRoute = require('./routes/home.route');
const adminRoute = require('./routes/admin.route');
const healthRoute = require('./routes/health.route');
const { securityHeaders } = require('./middleware/auth');
const { sanitizeInput } = require('./middleware/validation');
// Security middleware
app.use(securityHeaders);
app.use(helmet({
contentSecurityPolicy: {
directives: {
defaultSrc: ["'self'"],
styleSrc: ["'self'", "'unsafe-inline'", "https://cdnjs.cloudflare.com", "https://cdn.jsdelivr.net"],
scriptSrc: ["'self'", "'unsafe-inline'", "https://cdnjs.cloudflare.com", "https://cdn.jsdelivr.net"],
imgSrc: ["'self'", "data:", "https:"],
fontSrc: ["'self'", "https://cdnjs.cloudflare.com", "https://cdn.jsdelivr.net"],
connectSrc: ["'self'"],
frameSrc: ["'none'"],
objectSrc: ["'none'"]
}
}
}));
// Enable compression for better performance
app.use(compression());
// Rate limiting
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100, // Limit each IP to 100 requests per windowMs
message: {
error: 'Too many requests from this IP, please try again later.'
},
standardHeaders: true,
legacyHeaders: false,
});
app.use(limiter);
// Stricter rate limiting for authentication routes
const authLimiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 5, // Limit each IP to 5 login requests per windowMs
message: {
error: 'Too many login attempts, please try again later.'
},
standardHeaders: true,
legacyHeaders: false,
});
// CORS configuration
app.use(cors({
origin: process.env.NODE_ENV === 'production'
? ['https://sesclib.onrender.com'] // Your Render domain
: ['http://localhost:3000', 'http://localhost:4000'],
credentials: true,
methods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH'],
allowedHeaders: ['Content-Type', 'Authorization']
}));
// Logging middleware
if (process.env.NODE_ENV === 'production') {
app.use(morgan('combined'));
} else {
app.use(morgan('dev'));
}
// Set view engine
app.set('view engine', 'ejs');
app.use(express.static('public'));
app.use(express.json({ limit: '10mb' })); // Set payload limit
app.use(express.urlencoded({ extended: true, limit: '10mb' }));
app.use(sanitizeInput); // Sanitize all inputs
app.use(flash());
// Session configuration with better security
app.use(session({
secret: process.env.SESSION_SECRET || 'sescLib_chiheb_abiza', // Use environment variable
resave: false,
saveUninitialized: false,
cookie: {
secure: process.env.NODE_ENV === 'production', // Use secure cookies in production
httpOnly: true, // Prevent XSS attacks
maxAge: 24 * 60 * 60 * 1000, // 24 hours instead of 1 year
sameSite: 'strict' // CSRF protection
}
}));
// Middleware for flash messages
app.use((req, res, next) => {
res.locals.success = req.flash('success');
res.locals.error = req.flash('error');
next();
});
// Apply stricter rate limiting to auth routes
app.use('/login', authLimiter);
app.use('/register', authLimiter);
// Use routes
app.use('/', healthRoute);
app.use('/', homeRoute);
app.use('/', adminRoute);
// Global error handler
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).render('user/error', {
title: 'Server Error',
message: process.env.NODE_ENV === 'production'
? 'Something went wrong!'
: err.message
});
});
// 404 handler
app.use('*', (req, res) => {
res.status(404).render('user/404', {
title: 'Page Not Found',
url: req.originalUrl
});
});
// Graceful shutdown
process.on('SIGTERM', () => {
console.log('SIGTERM received, shutting down gracefully');
process.exit(0);
});
process.on('SIGINT', () => {
console.log('SIGINT received, shutting down gracefully');
process.exit(0);
});
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});