-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
274 lines (245 loc) · 7.99 KB
/
server.js
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
import express from 'express';
import cors from 'cors';
import mongoose from 'mongoose';
import bcrypt from 'bcryptjs';
import jwt from 'jsonwebtoken';
import dotenv from 'dotenv';
import { fileURLToPath } from 'url';
import { dirname } from 'path';
import passport from 'passport';
import { Strategy as GoogleStrategy } from 'passport-google-oauth20';
import path from 'path';
import fetch from 'node-fetch';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
// Load environment variables
dotenv.config();
const app = express();
// Environment configuration
const config = {
nodeEnv: process.env.NODE_ENV || 'development',
port: parseInt(process.env.PORT) || 5000,
baseUrl: process.env.NODE_ENV === 'production'
? 'https://thrillcompass.onrender.com'
: 'http://localhost:5000',
clientUrl: process.env.NODE_ENV === 'production'
? 'https://thrillcompass.onrender.com'
: 'http://localhost:3000',
mongodb: {
uri: process.env.MONGODB_URI
},
jwt: {
secret: process.env.JWT_SECRET
},
google: {
clientId: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
callbackUrl: process.env.NODE_ENV === 'production'
? 'https://thrillcompass.onrender.com/api/auth/google/callback'
: 'http://localhost:5000/api/auth/google/callback'
}
};
// Debug logging for configuration
console.log('[SERVER] Environment:', config.nodeEnv);
console.log('[SERVER] Base URL:', config.baseUrl);
console.log('[SERVER] Client URL:', config.clientUrl);
console.log('[SERVER] Google Callback URL:', config.google.callbackUrl);
console.log('[SERVER] MongoDB URI:', config.mongodb.uri ? 'Present' : 'Missing');
console.log('[SERVER] JWT Secret:', config.jwt.secret ? 'Present' : 'Missing');
console.log('[SERVER] Google Client ID:', config.google.clientId ? 'Present' : 'Missing');
// Serve static files from the React app first
app.use(express.static(path.join(__dirname, 'dist')));
// Middleware
app.use(cors({
origin: process.env.NODE_ENV === 'production'
? 'https://thrillcompass.onrender.com'
: 'http://localhost:3000',
credentials: true,
methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
allowedHeaders: ['Content-Type', 'Authorization']
}));
app.use(express.json());
app.use(passport.initialize());
// JWT Verification Middleware
const verifyToken = (req, res, next) => {
const authHeader = req.headers.authorization;
if (!authHeader) {
return res.status(401).json({ error: 'No token provided' });
}
const token = authHeader.split(' ')[1];
try {
const decoded = jwt.verify(token, process.env.JWT_SECRET);
req.userId = decoded.userId;
next();
} catch (error) {
return res.status(401).json({ error: 'Invalid token' });
}
};
// User Schema
const userSchema = new mongoose.Schema({
googleId: String,
email: String,
name: { type: String, required: true },
height: { type: Number, required: true },
ridePreferences: [{
rideId: { type: Number, required: true },
rating: { type: Number, required: true, min: 1, max: 5 }
}],
profileComplete: { type: Boolean, default: false }
});
const User = mongoose.model('User', userSchema);
// Passport Google Strategy
passport.use(new GoogleStrategy({
clientID: config.google.clientId,
clientSecret: config.google.clientSecret,
callbackURL: config.google.callbackUrl,
passReqToCallback: true
},
async function(request, accessToken, refreshToken, profile, done) {
try {
console.log('[Google Auth] Processing profile:', profile.id);
let user = await User.findOne({ googleId: profile.id });
if (!user) {
console.log('[Google Auth] Creating new user for:', profile.id);
user = await User.create({
googleId: profile.id,
email: profile.emails[0].value,
name: profile.displayName,
height: 65,
ridePreferences: [],
profileComplete: false
});
}
return done(null, user);
} catch (error) {
console.error('[Google Auth] Error:', error);
return done(error, null);
}
}
));
// Google Auth Routes
app.get('/api/auth/google',
passport.authenticate('google', { scope: ['profile', 'email'] })
);
app.get('/api/auth/google/callback',
passport.authenticate('google', { session: false }),
(req, res) => {
// Create JWT token
const token = jwt.sign(
{ userId: req.user._id },
config.jwt.secret,
{ expiresIn: '24h' }
);
// Redirect to frontend with token
const redirectUrl = `${config.clientUrl}/auth-callback?token=${token}`;
console.log('[Google Callback] Redirecting to:', redirectUrl);
res.redirect(redirectUrl);
}
);
// Profile Routes
app.post('/api/user/profile', verifyToken, async (req, res) => {
try {
const { name, height, rideId, rating } = req.body;
// If updating a single ride rating
if (rideId !== undefined && rating !== undefined) {
const user = await User.findById(req.userId);
if (!user) {
return res.status(404).json({ error: 'User not found' });
}
// Find existing preference or create new one
const existingPrefIndex = user.ridePreferences.findIndex(pref => pref.rideId === rideId);
if (existingPrefIndex !== -1) {
// Update existing preference
user.ridePreferences[existingPrefIndex].rating = rating;
} else {
// Add new preference
user.ridePreferences.push({ rideId, rating });
}
// Save the updated user
const updatedUser = await user.save();
return res.json(updatedUser);
}
// If updating profile (name and height only)
if (!name || !height) {
return res.status(400).json({ error: 'Invalid profile data' });
}
// Use $set to only update specific fields
const updatedUser = await User.findByIdAndUpdate(
req.userId,
{
$set: {
name,
height: parseInt(height),
profileComplete: true
}
},
{ new: true }
);
if (!updatedUser) {
return res.status(404).json({ error: 'User not found' });
}
res.json(updatedUser);
} catch (error) {
console.error('Profile update error:', error);
res.status(500).json({ error: error.message });
}
});
// Get user profile
app.get('/api/user/profile', verifyToken, async (req, res) => {
try {
const user = await User.findById(req.userId);
if (!user) {
return res.status(404).json({ error: 'User not found' });
}
res.json(user);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// Queue Times Route
app.get('/api/queue-times/:parkId', async (req, res) => {
try {
const parkId = req.params.parkId;
console.log(`[Queue Times] Fetching data for park ${parkId}`);
const response = await fetch(`https://queue-times.com/parks/${parkId}/queue_times.json`);
if (!response.ok) {
throw new Error(`Failed to fetch queue times for park ${parkId}`);
}
const data = await response.json();
res.json(data);
} catch (error) {
console.error('Queue times error:', error);
res.status(500).json({ error: 'Failed to fetch queue times' });
}
});
// Connect to MongoDB with robust error handling
mongoose.connect(process.env.MONGODB_URI, {
serverSelectionTimeoutMS: 30000,
socketTimeoutMS: 45000,
connectTimeoutMS: 30000,
waitQueueTimeoutMS: 30000,
retryWrites: true,
w: 'majority',
useNewUrlParser: true,
useUnifiedTopology: true
})
.then(() => {
console.log('[MongoDB] Connected successfully');
// Use port 5000 by default for the backend
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
console.log(`[SERVER] Running on port ${PORT}`);
});
})
.catch(err => {
console.error('[MongoDB] Connection error:', err);
process.exit(1);
});
// Move the catch-all route to the end
app.get('*', (req, res) => {
// Don't serve the frontend for API routes
if (req.path.startsWith('/api/')) {
return res.status(404).json({ error: 'API endpoint not found' });
}
res.sendFile(path.join(__dirname, 'dist', 'index.html'));
});