-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.js
More file actions
252 lines (221 loc) Β· 8.94 KB
/
server.js
File metadata and controls
252 lines (221 loc) Β· 8.94 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
import express from 'express';
import dotenv from 'dotenv';
import cors from 'cors';
import cookieParser from 'cookie-parser';
import session from 'express-session';
import path from 'path';
import { fileURLToPath } from 'url';
import createRoutes from './routes/create/createRoutes.js';
import { passport } from './routes/create/middleware/passport.js';
import connectDB from './routes/create/config/database.js';
import mongoose from 'mongoose';
// ES6 __dirname equivalent
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
// Load environment variables from .env file
dotenv.config();
console.log('π Starting TLEF-CREATE server...');
console.log('π¦ Environment:', process.env.NODE_ENV || 'development');
console.log('π Port:', process.env.PORT || 7736);
console.log('π Frontend URL:', process.env.FRONTEND_URL || 'not set');
// Connect to database
console.log('π Connecting to MongoDB...');
connectDB().catch(err => {
console.error('β Failed to connect to MongoDB:', err.message);
// Don't exit immediately in production to allow health checks
if (process.env.NODE_ENV !== 'production') {
process.exit(1);
}
});
// Initialize RAG service on server startup
console.log('π§ Initializing RAG service...');
import('./routes/create/services/ragService.js')
.then(module => {
const ragService = module.default;
console.log('β
RAG service import successful');
// The service will initialize itself asynchronously
})
.catch(err => {
console.error('β Failed to import RAG service:', err.message);
console.error('π‘ RAG features may not work properly');
});
// Initialize system prompt templates on server startup
console.log('π§ Initializing system prompt templates...');
import('./routes/create/services/promptTemplateInitializer.js')
.then(module => {
module.initializePromptTemplates();
})
.catch(err => {
console.error('β Failed to initialize prompt templates:', err.message);
console.error('π‘ Prompt template features may not work properly');
});
// Initialize Lumi H5P server
console.log('π§ Initializing Lumi H5P server...');
import('./routes/create/services/lumiService.js')
.then(module => module.initializeLumi())
.then(() => console.log('β
Lumi H5P server ready'))
.catch(err => {
console.error('β Failed to initialize Lumi:', err.message);
console.error('π‘ Canvas H5P export may not work properly');
});
// Start LTI 1.3 server (separate port) β only if configured
if (process.env.LTI_CLIENT_ID) {
console.log('π§ Starting LTI 1.3 server...');
import('./routes/create/services/ltiService.js')
.then(module => module.startLtiServer())
.catch(err => {
console.error('β Failed to start LTI server:', err.message);
console.error('π‘ Canvas LTI integration may not work properly');
});
} else {
console.log('βΉοΈ LTI_CLIENT_ID not set β LTI server skipped (Canvas grade passback unavailable)');
}
const app = express();
const PORT = process.env.PORT || 7736;
// CORS configuration for frontend integration
// In production, strip port numbers from FRONTEND_URL as they shouldn't be in browser requests
let corsOrigin;
if (process.env.NODE_ENV === 'production') {
if (process.env.FRONTEND_URL) {
// Remove port from URL (e.g., https://domain.com:8092 -> https://domain.com)
corsOrigin = process.env.FRONTEND_URL.replace(/:\d+$/, '');
console.log('π CORS origin set to:', corsOrigin);
} else {
corsOrigin = true; // Allow same-origin
}
} else {
corsOrigin = ['http://localhost:3000', 'http://localhost:8080', 'http://localhost:8081', 'http://localhost:8090', 'http://localhost:8092', 'http://localhost:8093', 'http://tlef-create-dev.com:7737'];
}
app.use(cors({
origin: corsOrigin,
credentials: true,
methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
allowedHeaders: ['Content-Type', 'Authorization']
}));
// Middleware - limits for file uploads (reduced from 100mb to 50mb for safety)
app.use(express.json({ limit: '50mb' }));
app.use(express.urlencoded({ extended: true, limit: '50mb' }));
app.use(cookieParser());
// Session middleware for passport
// For staging/production behind proxy, we need to trust the proxy
if (process.env.NODE_ENV === 'production') {
app.set('trust proxy', 1); // Trust first proxy (nginx)
}
// HARDCODED FIX FOR STAGING: Disable secure cookies for staging environment
const isStaging = process.env.NODE_ENV === 'production' &&
(process.env.FRONTEND_URL?.includes('staging') ||
process.env.PORT === '8090');
// Session configuration with environment-specific cookie settings
const sessionConfig = {
secret: process.env.SESSION_SECRET || 'your-secret-key-change-in-production',
resave: false,
saveUninitialized: false,
cookie: {
httpOnly: true,
maxAge: 24 * 60 * 60 * 1000, // 24 hours
...(process.env.NODE_ENV === 'production'
? { secure: false, sameSite: 'lax' } // Production/staging: CSRF protection
: { sameSite: false } // Development: allow cross-port cookies
)
},
name: 'tlef.sid' // Custom session name
};
app.use(session(sessionConfig));
// Initialize passport
app.use(passport.initialize());
app.use(passport.session());
// Health check endpoint (before other routes for priority)
app.get('/health', (_req, res) => {
res.json({
status: 'ok',
timestamp: new Date().toISOString(),
environment: process.env.NODE_ENV || 'development',
port: PORT,
mongodb: mongoose.connection.readyState === 1 ? 'connected' : 'disconnected'
});
});
// Test endpoint to verify nginx routing
app.get('/api/test', (_req, res) => {
res.json({
message: 'Backend is working!',
timestamp: new Date().toISOString(),
server: 'TLEF-CREATE Staging'
});
});
// HARDCODED: Debug middleware for staging - always on for debugging auth issues
if (process.env.NODE_ENV === 'production') {
app.use((req, _res, next) => {
// Only log API auth endpoints to reduce noise
if (req.path.includes('/auth/')) {
console.log('π Auth Request:', req.method, req.path);
console.log('πͺ Cookies:', req.cookies);
console.log('π¦ Session ID:', req.sessionID);
console.log('π€ User:', req.user ? req.user.cwlId : 'none');
console.log('β
Authenticated:', req.isAuthenticated ? req.isAuthenticated() : false);
}
next();
});
}
// SAML Shibboleth.sso compatibility route
// UBC's IdP metadata uses /Shibboleth.sso/SAML2/POST, so redirect to our Express callback
app.post('/Shibboleth.sso/SAML2/POST', (req, res) => {
console.log('π Redirecting Shibboleth.sso callback to /api/create/auth/saml/callback');
// Forward the request to the actual SAML callback handler
req.url = '/api/create/auth/saml/callback';
app.handle(req, res);
});
// Static serving for extracted H5P preview files (before API routes to avoid rate limiting)
app.use('/h5p-preview-files', express.static(path.join(__dirname, 'routes', 'create', 'uploads', 'h5p-preview')));
// Mount the API router FIRST (before static files)
app.use('/api/create', createRoutes);
// Serve static files from dist in production
if (process.env.NODE_ENV === 'production') {
// Log static file serving for debugging
console.log('π Serving static files from:', path.join(__dirname, 'dist'));
// Serve static files
app.use(express.static(path.join(__dirname, 'dist')));
// Handle SPA routing - serve index.html for all non-API routes
app.get('*', (req, res) => {
// Don't serve SPA for API routes
if (req.path.startsWith('/api/')) {
console.log('β API endpoint not found:', req.path);
return res.status(404).json({ error: 'API endpoint not found' });
}
const indexPath = path.join(__dirname, 'dist', 'index.html');
console.log('π Serving index.html for:', req.path);
res.sendFile(indexPath);
});
} else {
// Development mode - show server status
app.get('/', (_req, res) => {
res.json({
message: 'TLEF Web Server is running in development mode',
api: `/api/create`,
frontend: 'Run `npm run dev` for frontend development server'
});
});
}
// Error handling middleware
app.use((err, _req, res, _next) => {
console.error('β Unhandled error:', err);
res.status(500).json({
error: 'Internal server error',
message: process.env.NODE_ENV === 'production' ? 'An error occurred' : err.message
});
});
const server = app.listen(PORT, '0.0.0.0', () => {
console.log(`β
Server is running on http://localhost:${PORT}`);
console.log(`π‘ Health check available at http://localhost:${PORT}/health`);
console.log(`π― CREATE app API available at http://localhost:${PORT}/api/create`);
});
// Graceful shutdown
process.on('SIGTERM', () => {
console.log('π SIGTERM signal received: closing HTTP server');
server.close(async () => {
console.log('π΄ HTTP server closed');
// Mongoose 8+ doesn't accept callbacks for close()
await mongoose.connection.close();
console.log('π΄ MongoDB connection closed');
process.exit(0);
});
});