-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
335 lines (281 loc) · 10.6 KB
/
Copy pathindex.js
File metadata and controls
335 lines (281 loc) · 10.6 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
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
import path from 'path';
import fs from 'fs';
import { fileURLToPath } from 'url';
//Loads the config fomr config.env to process.env (turn off prior to deployment)
import dotenv from "dotenv";
dotenv.config({ path: "./.env" });
import axios from 'axios';
import express from 'express';
import session from 'express-session';
import helmet from 'helmet';
import rateLimit from 'express-rate-limit';
import passport from './passport.js'; // Import the passport module
import authRoutes from './routes/auth.js'; // Import the authentication routes module
import methodOverride from 'method-override';
import csurf from 'csurf';
import { ensureAuthenticated } from './middleware/auth.js';
import { connectDB } from './config/database.js';
// Get __dirname equivalent for ES modules
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const app = express();
app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ extended: true, limit: '10mb' }));
app.use(methodOverride('_method'));
app.set('view engine', 'ejs');
// Session configuration
app.use(session({
resave: false,
saveUninitialized: false, // Only create sessions for authenticated users
secret: process.env.SESSION_SECRET,
cookie: {
secure: process.env.NODE_ENV === 'production', // Only use HTTPS in production
httpOnly: true, // Prevent XSS access to cookies
sameSite: 'lax', // Allow cross-site requests for OAuth callbacks
maxAge: 24 * 60 * 60 * 1000 // 24 hour session timeout
},
name: 'odi-session' // Change default session cookie name
}));
// Initialize Passport.js
app.use(passport.initialize());
app.use(passport.session());
app.use(function(req, res, next) {
res.locals.user = req.session.passport ? req.session.passport.user : req.session.user;
next();
});
app.use((req, res, next) => {
// Read package.json file
fs.readFile(path.join(__dirname, 'package.json'), 'utf8', (err, data) => {
if (err) {
console.error('Error reading package.json:', err);
return next();
}
try {
const packageJson = JSON.parse(data);
// Extract version from package.json
var software = {};
software.version = packageJson.version;
software.homepage = packageJson.homepage;
software.versionLink = packageJson.homepage + "/releases/tag/v" + packageJson.version;
res.locals.software = software;
} catch (error) {
console.error('Error parsing package.json:', error);
}
next();
});
});
app.use((req, res, next) => {
res.setHeader('Cache-Control', 'no-cache, no-store, must-revalidate'); // HTTP 1.1.
res.setHeader('Pragma', 'no-cache'); // HTTP 1.0.
res.setHeader('Expires', '0'); // Proxies.
next();
});
// Security headers and middleware
app.disable('x-powered-by');
app.use(helmet({
contentSecurityPolicy: {
useDefaults: true,
directives: {
"default-src": ["'self'"],
"script-src": ["'self'", "'unsafe-inline'"],
"style-src": ["'self'", "'unsafe-inline'"],
"img-src": ["'self'", 'data:'],
"object-src": ["'none'"],
"base-uri": ["'self'"],
"frame-ancestors": ["'none'"]
}
},
referrerPolicy: { policy: 'strict-origin-when-cross-origin' },
hsts: process.env.NODE_ENV === 'production' ? {
maxAge: 60 * 60 * 24 * 365,
includeSubDomains: true,
preload: true
} : false
}));
/* Setup public directory
* Everything in her does not require authentication */
app.use(express.static(__dirname + '/public'));
// Rate limiting
const authLimiter = rateLimit({
windowMs: 15 * 60 * 1000,
max: 100,
standardHeaders: true,
legacyHeaders: false
});
const publicLimiter = rateLimit({
windowMs: 5 * 60 * 1000,
max: 60,
standardHeaders: true,
legacyHeaders: false
});
// Apply rate limiting BEFORE mounting routers
app.use('/auth', authLimiter);
// Use authentication routes
app.use('/auth', authRoutes);
// CSRF protection: generate token on all non-exempt routes; enforce on non-safe methods
const csrfProtection = csurf(); // defaults ignoreMethods: ['GET','HEAD','OPTIONS']
app.use((req, res, next) => {
const skip = req.path.startsWith('/auth/')
|| req.path.startsWith('/webhooks')
|| req.path.startsWith('/enrollments/verify')
|| req.path.startsWith('/enrollments/status');
if (skip) return next();
return csrfProtection(req, res, next);
});
// Expose CSRF token to views on pages where middleware ran
app.use((req, res, next) => {
if (typeof req.csrfToken === 'function') {
try { res.locals.csrfToken = req.csrfToken(); } catch (_) {}
}
next();
});
// Basic input sanitization middleware
app.use((req, res, next) => {
// Sanitize query parameters
if (req.query) {
Object.keys(req.query).forEach(key => {
if (typeof req.query[key] === 'string') {
req.query[key] = req.query[key].trim().replace(/[<>]/g, '');
}
});
}
// Sanitize body parameters (for non-file uploads)
if (req.body && req.headers['content-type'] !== 'multipart/form-data') {
Object.keys(req.body).forEach(key => {
if (typeof req.body[key] === 'string') {
req.body[key] = req.body[key].trim().replace(/[<>]/g, '');
}
});
}
next();
});
app.get('/', function(req, res) {
const page = {
title: "Orchestrator",
link: "/"
};
res.locals.page = page;
res.render('pages/home');
});
/* Setup private directory, everything in here requires authentication */
app.use('/private', ensureAuthenticated);
app.use('/private', express.static(__dirname + '/private'));
// Import Routes
import forecastRoutes from "./routes/forecast.js";
app.use("/forecast", ensureAuthenticated, forecastRoutes);
import hubspotRoutes from "./routes/hubspot.js";
app.use("/hubspot", ensureAuthenticated, hubspotRoutes);
import calendarRoutes from "./routes/calendar.js";
app.use("/calendar", ensureAuthenticated, calendarRoutes);
import courseBookingsRoutes from "./routes/courseBookings.js";
app.use("/course-bookings", ensureAuthenticated, courseBookingsRoutes);
import moodleRoutes from "./routes/moodle.js";
app.use("/moodle", ensureAuthenticated, moodleRoutes);
// Public enrollment verification routes (no authentication required)
import enrollmentVerificationRoutes from "./routes/enrollmentVerification.js";
app.use("/enrollments/verify", publicLimiter, enrollmentVerificationRoutes);
// Public status check: ?course_id=123&email=user@example.com
import EnrollmentController from "./controllers/EnrollmentController.js";
const publicEnrollmentController = new EnrollmentController();
app.get('/enrollments/status', publicLimiter, (req, res) => publicEnrollmentController.getUserCourseStatus(req, res));
import enrollmentRoutes from "./routes/enrollments.js";
app.use("/enrollments", ensureAuthenticated, enrollmentRoutes);
import selfPacedBookingsRoutes from "./routes/selfPacedBookings.js";
app.use("/self-paced-bookings", ensureAuthenticated, selfPacedBookingsRoutes);
// Webhooks (public, authenticated by API key inside controller)
import webhooksRoutes from "./routes/webhooks.js";
app.use("/webhooks", publicLimiter, webhooksRoutes);
// Manual/help routes
import manualRoutes from "./routes/manual.js";
app.use("/manual", ensureAuthenticated, manualRoutes);
// Lightweight background refresh (interval-based)
import MoodleCacheService from './services/moodleCacheService.js';
import HubSpotCacheService from './services/hubspotCacheService.js';
const scheduler = {
started: false,
start() {
if (this.started) return;
this.started = true;
const moodle = new MoodleCacheService();
const hubspot = new HubSpotCacheService();
const moodleIntervalMs = parseInt(process.env.MOODLE_CACHE_INTERVAL_MS || `${15 * 60 * 1000}`, 10);
const hubspotIntervalMs = parseInt(process.env.HUBSPOT_CACHE_INTERVAL_MS || `${60 * 60 * 1000}`, 10);
setInterval(() => {
moodle.refreshCoursesBatch({ concurrency: parseInt(process.env.MOODLE_CONCURRENCY || '5', 10) }).catch(() => {});
}, moodleIntervalMs);
// HubSpot membership refresh requires a list of emails; for minimal setup we no-op here.
// You can later wire a query of recent emails from Moodle cache and pass to refreshMemberships.
setInterval(async () => {
try {
const MoodleCourseEnrollments = (await import('./models/MoodleCourseEnrollments.js')).default;
const docs = await MoodleCourseEnrollments.find({}, { 'enrollments.email': 1 }).limit(1000).lean();
const emails = [];
for (const d of docs) {
for (const u of (d.enrollments || [])) {
if (u.email) emails.push(u.email.toLowerCase());
}
}
await hubspot.refreshMemberships(emails, { concurrency: parseInt(process.env.HUBSPOT_CONCURRENCY || '4', 10) });
} catch (_) {}
}, hubspotIntervalMs);
}
};
//Keep this at the END!
app.get('*', function(req, res){
const page = {
title: "404 Not Found"
};
res.locals.page = page;
// Content negotiation based on request Accept header
const acceptHeader = req.get('Accept');
if (acceptHeader === 'application/json') {
// Respond with JSON
res.status(404).json({ message: "Not Found" });
} else {
// Respond with HTML (rendering an error page)
res.status(404).render('errors/error', { statusCode: 404, errorMessage: "Not Found" });
}
});
// Error handling middleware
app.use((err, req, res, next) => {
// Default status code for unhandled errors
let statusCode = 500;
let errorMessage = "Internal Server Error";
// Check if the error has a specific status code and message
if (err.status) {
statusCode = err.status;
errorMessage = err.message;
}
const page = {
title: "Error"
};
res.locals.page = page;
// Only log actual errors (not 404s) with minimal info
if (statusCode !== 404) {
console.log(`Error ${statusCode}: ${errorMessage} - ${req.method} ${req.path}`);
}
// Content negotiation based on request Accept header
const acceptHeader = req.get('Accept');
if (acceptHeader === 'application/json') {
// Respond with JSON
res.status(statusCode).json({ message: errorMessage });
} else {
// Respond with HTML (rendering an error page)
res.status(statusCode).render('errors/error', { statusCode, errorMessage });
}
});
/* Run server */
const port = process.env.PORT || 3080;
// Connect to MongoDB before starting the server
const startServer = async () => {
try {
await connectDB();
// start background schedulers once DB is ready
try { scheduler.start(); } catch (_) {}
app.listen(port, () => console.log('App listening on port ' + port));
} catch (error) {
console.error('Failed to start server:', error);
process.exit(1);
}
};
startServer();