forked from Ammaar-Alam/tigertype
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
294 lines (264 loc) · 10.8 KB
/
server.js
File metadata and controls
294 lines (264 loc) · 10.8 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
/**
* TigerType Server
* A Princeton-themed typing platform for speed typing practice and races
*/
// Load environment variables from .env file
require('dotenv').config();
const express = require('express');
const session = require('express-session');
const path = require('path');
const http = require('http');
const os = require('os');
const socketIO = require('socket.io');
const { isAuthenticated, logoutApp, logoutCAS } = require('./server/utils/auth');
const routes = require('./server/routes');
const socketHandler = require('./server/controllers/socket-handlers');
const db = require('./server/db');
const cors = require('cors');
const fs = require('fs');
const pgSession = require('connect-pg-simple')(session);
const { pool } = require('./server/config/database');
const { initDB, logDatabaseState } = require('./server/db');
const { runMigrations } = require('./server/db/migrations');
const { URL } = require('url');
const app = express();
const server = http.createServer(app);
const io = socketIO(server, {
cors: {
origin: process.env.NODE_ENV === 'production' ? process.env.SERVICE_URL : 'http://localhost:5174',
methods: ['GET', 'POST'],
credentials: true
},
transports: ['websocket', 'polling'],
pingTimeout: 60000,
pingInterval: 25000
});
// --- Trust Proxy ---
app.set('trust proxy', true); // Use true for built-in trust
app.use((req, res, next) => {
// Fix HTTPS detection through Cloudflare
if (req.headers['x-forwarded-proto'] === 'https' ||
req.headers['cf-visitor'] && JSON.parse(req.headers['cf-visitor']).scheme === 'https') {
req.protocol = 'https';
req.secure = true;
}
next();
});
// --- CORS ---
const corsOptions = {
origin: process.env.NODE_ENV === 'production' ? process.env.SERVICE_URL : 'http://localhost:5174',
credentials: true,
methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
allowedHeaders: ['Content-Type', 'Authorization', 'Cookie'],
exposedHeaders: ['Set-Cookie']
};
app.use(cors(corsOptions));
// --- Cookie Domain Logic ---
let cookieDomain;
const isProd = process.env.NODE_ENV === 'production';
try {
const serviceUrl = process.env.SERVICE_URL;
if (isProd && serviceUrl) {
const serviceUrlHostname = new URL(serviceUrl).hostname;
// Set domain ONLY for the custom domain, not for default herokuapp.com domains
if (!serviceUrlHostname.endsWith('herokuapp.com')) {
cookieDomain = serviceUrlHostname;
console.log(`COOKIE DOMAIN: Calculated cookie domain for production: ${cookieDomain}`);
} else {
console.log('COOKIE DOMAIN: Running on default Heroku domain, cookie domain not explicitly set.');
}
} else {
console.log(`COOKIE DOMAIN: Not in production (isProd=${isProd}) or SERVICE_URL not set, cookie domain not explicitly set.`);
}
} catch (e) {
console.error("Error parsing SERVICE_URL for cookie domain:", e);
}
// Log the final value being used
console.log(`COOKIE DOMAIN: Effective value being used: ${cookieDomain}`);
app.use((req, res, next) => {
// console.log('[DIAGNOSTIC LOG] Path:', req.path);
// console.log('[DIAGNOSTIC LOG] Headers:', {
// host: req.headers.host,
// 'x-forwarded-proto': req.headers['x-forwarded-proto'],
// 'x-forwarded-for': req.headers['x-forwarded-for'],
// cookie: req.headers.cookie ? 'Present' : 'None'
// });
// Force HTTPS protocol detection when behind Cloudflare or Heroku
if (process.env.NODE_ENV === 'production') {
// This allows secure cookies to work even if the request appears as HTTP
req.headers['x-forwarded-proto'] = 'https';
}
// console.log('[DIAGNOSTIC LOG] req.protocol:', req.protocol, 'req.secure:', req.secure);
next();
});
// --- Session Middleware ---
const sessionMiddleware = session({
store: new pgSession({
pool: pool,
tableName: 'user_sessions',
errorLog: console.error.bind(console, 'Postgres Session Store Error:')
}),
secret: process.env.SESSION_SECRET,
resave: false,
saveUninitialized: false,
rolling: true,
name: 'connect.sid',
proxy: true,
cookie: {
secure: process.env.NODE_ENV === 'production', // Secure in production, but we'll force HTTPS
path: '/',
httpOnly: true,
maxAge: 24 * 60 * 60 * 1000, // 24 hours
sameSite: process.env.NODE_ENV === 'production' ? 'none' : 'lax',
domain: cookieDomain,
}
});
app.use(sessionMiddleware);
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// --- Static files and Routes ---
if (process.env.NODE_ENV === 'production') {
app.use(express.static(path.join(__dirname, 'client/dist')));
console.log('Production mode: Serving static files from client/dist');
// API/Auth routes BEFORE catch-all
app.use(routes);
// SPA Catch-all
app.get('*', (req, res) => {
// Check auth status *before* sending index.html for non-API routes
// to potentially redirect unauth users to login immediately
if (!isAuthenticated(req) && !req.path.startsWith('/api/') && !req.path.startsWith('/auth/')) {
// If trying to access a frontend route other than /, redirect to start auth flow
console.log(`Unauthenticated access to SPA route ${req.path}, redirecting to /auth/login`);
return res.redirect('/auth/login'); // Or just res.redirect('/') which triggers casAuth
}
// Serve index.html for authenticated users or allowed paths
const indexPath = path.join(__dirname, 'client/dist/index.html');
res.sendFile(indexPath, (err) => {
if (err) {
console.error(`Error sending file ${indexPath}:`, err);
res.status(500).send('Error serving application.');
}
});
});
} else { // Development mode
app.use(routes);
app.get('/', (req, res) => {
res.json({ message: 'TigerType API Server', /* ... */ });
});
}
// --- Socket.IO Setup ---
io.use((socket, next) => {
console.log('Socket middleware: sharing session...');
sessionMiddleware(socket.request, socket.request.res || {}, next); // Pass res if available
});
io.use(async (socket, next) => {
const req = socket.request;
console.log('Socket middleware: authenticating connection...', socket.id);
// Debug: Log session state at start
console.log('Socket Auth - Session ID:', req.sessionID);
// console.log('Socket Auth - Session Data:', JSON.stringify(req.session)); // Careful with sensitive data
if (!isAuthenticated(req)) {
console.error(`Socket authentication failed for socket ${socket.id}: User not authenticated in session.`);
return next(new Error('Authentication required'));
}
try {
if (!req.session || !req.session.userInfo || !req.session.userInfo.user) {
console.error(`Socket authentication failed for socket ${socket.id}: Session or userInfo missing.`);
return next(new Error('Invalid session state'));
}
const netid = req.session.userInfo.user;
const UserModel = require('./server/models/user');
const user = await UserModel.findOrCreate(netid);
if (!user || !user.id) {
console.error(`Socket authentication failed for socket ${socket.id}: Could not find/create user for ${netid}`);
return next(new Error('Failed to identify user in database'));
}
socket.userInfo = {
...(req.session.userInfo || {}),
userId: user.id,
netid: user.netid
};
if (!req.session.userInfo.userId) {
req.session.userInfo.userId = user.id;
req.session.save(err => {
if (err) {
console.error(`Error saving session during socket auth for socket ${socket.id}:`, err);
} else {
console.log(`Session updated with userId during socket auth for socket ${socket.id}`);
}
});
}
console.log(`Socket auth success for socket ${socket.id} (netid: ${netid}, userId: ${user.id})`);
next();
} catch (err) {
console.error(`Socket authentication error for socket ${socket.id}:`, err);
return next(new Error('Authentication error'));
}
});
socketHandler.initialize(io);
// --- Server Start ---
const startServer = async () => {
try {
console.log(`${process.env.NODE_ENV} mode detected - checking database state...`);
try {
const db = require('./server/db');
await db.initDB();
console.log('Database initialized successfully.');
console.log('Running database migrations...');
await runMigrations();
console.log('Database migrations completed.');
try {
const client = await pool.connect();
try {
// check for users with null/0 fastest_wpm but have race results > 0
const result = await client.query(`
SELECT COUNT(*) FROM users
WHERE (fastest_wpm IS NULL OR fastest_wpm = 0)
AND id IN (SELECT DISTINCT user_id FROM race_results WHERE wpm > 0)
`);
const discrepancyCount = parseInt(result.rows[0].count);
if (discrepancyCount > 0) {
console.log(`Found ${discrepancyCount} users with fastest_wpm = 0/null but have race results > 0`);
const dbHelpers = require('./server/utils/db-helpers'); // Ensure db-helpers is required correctly
await dbHelpers.updateAllUsersFastestWpm();
console.log('Fixed fastest_wpm discrepancies');
} else {
console.log('No fastest_wpm discrepancies found');
}
} finally {
client.release();
}
} catch (err) {
console.error('Error checking/fixing fastest_wpm discrepancies:', err);
}
} catch (err) {
console.error('Database initialization failed:', err);
console.log('Continuing server startup despite database initialization failure');
}
const port = process.env.PORT || 3000;
server.listen(port, () => {
console.log(`Server running on port ${port}`);
console.log(`Environment: ${process.env.NODE_ENV}`);
console.log(`Frontend URL: ${process.env.NODE_ENV === 'production' ? process.env.SERVICE_URL : 'http://localhost:5174'}`);
console.log(`Cookie Domain Configured: ${cookieDomain || 'Default (Host Only)'}`);
if (!process.env.SESSION_SECRET || process.env.SESSION_SECRET === 'tigertype-fallback-secret-change-me') {
console.warn('WARNING: SESSION_SECRET is not set or using the insecure default. Please set a strong secret in Heroku Config Vars.');
} else {
console.log('SESSION_SECRET is set.');
}
// Log the intended cookie settings using the variables available
console.log('Effective Cookie Settings Expected:', JSON.stringify({
secure: isProd,
path: '/',
httpOnly: true,
maxAge: 24 * 60 * 60 * 1000,
sameSite: 'lax',
domain: cookieDomain,
}));
});
} catch (err) {
console.error('Failed to start server:', err);
process.exit(1);
}
};
startServer();