-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
475 lines (372 loc) · 16.8 KB
/
Copy pathindex.js
File metadata and controls
475 lines (372 loc) · 16.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
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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
require('dotenv').config();
const express = require('express');
const cors = require('cors');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const { createClient } = require('@supabase/supabase-js');
const path = require('path');
const app = express();
const PORT = process.env.PORT || 5000;
const SECRET_KEY = process.env.SECRET_KEY || 'super_secret_key';
// Initialize Supabase
const supabaseUrl = process.env.SUPABASE_URL;
const supabaseKey = process.env.SUPABASE_KEY;
if (!supabaseUrl || !supabaseKey) {
console.error('Error: SUPABASE_URL and SUPABASE_KEY are required in .env file');
}
const supabase = createClient(supabaseUrl, supabaseKey);
// Middleware
app.use(cors());
app.use(express.json());
// Serve static files from the React app
app.use(express.static(path.join(__dirname, 'client/dist')));
// --- Auth Routes ---
// Register
app.post('/api/auth/register', async (req, res) => {
const { name, email, password, university, skills, profile_photo } = req.body;
const hashedPassword = bcrypt.hashSync(password, 8);
const skillsString = Array.isArray(skills) ? skills.join(',') : skills;
const { data: existing, error: findError } = await supabase.from('users').select('id').eq('email', email).maybeSingle();
if (existing) {
return res.status(400).json({ error: 'User already exists.' });
}
const { error } = await supabase.from('users').insert([
{ name, email, password: hashedPassword, university, skills: skillsString, profile_photo }
]);
if (error) return res.status(500).json({ error: error.message });
res.json({ message: 'User registered successfully!' });
});
// Login
app.post('/api/auth/login', async (req, res) => {
const { email, password } = req.body;
const { data: user, error } = await supabase.from('users').select('*').eq('email', email).single();
if (error || !user) return res.status(404).json({ error: 'User not found.' });
const validPassword = bcrypt.compareSync(password, user.password);
if (!validPassword) return res.status(401).json({ error: 'Invalid password.' });
const token = jwt.sign({ id: user.id }, SECRET_KEY, { expiresIn: '24h' });
res.json({ token, user: { id: user.id, name: user.name, email: user.email, profile_photo: user.profile_photo } });
});
// Google Login
app.post('/api/auth/google', async (req, res) => {
const { email, name, profile_photo, google_id } = req.body;
// Check if user exists
let { data: user, error } = await supabase.from('users').select('*').eq('email', email).maybeSingle();
if (!user) {
// Create new user
// Note: Password is required by schema usually, but for OAuth we can set a dummy one or make it nullable.
// Assuming we need a password, we generate a random one.
const dummyPassword = bcrypt.hashSync(Math.random().toString(36).slice(-8), 8);
const { data: newUser, error: createError } = await supabase.from('users').insert([
{ name, email, password: dummyPassword, university: '', skills: '', profile_photo }
]).select().single();
if (createError) return res.status(500).json({ error: createError.message });
user = newUser;
}
const token = jwt.sign({ id: user.id }, SECRET_KEY, { expiresIn: '24h' });
res.json({ token, user: { id: user.id, name: user.name, email: user.email, profile_photo: user.profile_photo } });
});
// Multer setup for file uploads (memory storage)
const multer = require('multer');
const upload = multer({
storage: multer.memoryStorage(),
limits: { fileSize: 5 * 1024 * 1024 } // 5MB limit
});
// Update Profile
app.put('/api/auth/profile', upload.single('profile_photo'), async (req, res) => {
const token = req.headers.authorization?.split(' ')[1];
if (!token) return res.status(401).json({ error: 'Unauthorized' });
try {
const decoded = jwt.verify(token, SECRET_KEY);
const { name, university, skills } = req.body;
let { profile_photo } = req.body;
const skillsString = Array.isArray(skills) ? skills.join(',') : skills;
// Handle File Upload
if (req.file) {
const file = req.file;
const fileExt = file.originalname.split('.').pop();
const fileName = `${decoded.id}-${Date.now()}.${fileExt}`;
const filePath = `${fileName}`;
const { data, error: uploadError } = await supabase
.storage
.from('profile-photos')
.upload(filePath, file.buffer, {
contentType: file.mimetype
});
if (uploadError) return res.status(500).json({ error: `Upload failed: ${uploadError.message}` });
// Get Public URL
const { data: { publicUrl } } = supabase
.storage
.from('profile-photos')
.getPublicUrl(filePath);
profile_photo = publicUrl;
}
const { data, error } = await supabase
.from('users')
.update({ name, university, skills: skillsString, profile_photo })
.eq('id', decoded.id)
.select('id, name, email, university, skills, profile_photo')
.single();
if (error) return res.status(500).json({ error: error.message });
res.json(data);
} catch (err) {
console.error(err);
return res.status(401).json({ error: 'Unauthorized or invalid request' });
}
});
// Get Current User (Me)
app.get('/api/auth/me', async (req, res) => {
const token = req.headers.authorization?.split(' ')[1];
if (!token) return res.status(401).json({ error: 'No token provided' });
try {
const decoded = jwt.verify(token, SECRET_KEY);
const { data: user, error } = await supabase
.from('users')
.select('id, name, email, university, skills, profile_photo')
.eq('id', decoded.id)
.single();
if (error || !user) return res.status(404).json({ error: 'User not found' });
res.json(user);
} catch (err) {
return res.status(500).json({ error: 'Failed to authenticate token' });
}
});
// --- Hackathon Routes ---
// Get All Hackathons
app.get('/api/hackathons', async (req, res) => {
const { data, error } = await supabase.from('hackathons').select('*');
if (error) return res.status(500).json({ error: error.message });
res.json(data);
});
// Create Hackathon
app.post('/api/hackathons', async (req, res) => {
const token = req.headers.authorization?.split(' ')[1];
if (!token) return res.status(401).json({ error: 'Unauthorized' });
try {
const decoded = jwt.verify(token, SECRET_KEY);
// Get user name
const { data: user, error: userError } = await supabase.from('users').select('name').eq('id', decoded.id).single();
if (userError) return res.status(401).json({ error: 'Unauthorized' });
const { title, description, start_date, max_team_size, type, url } = req.body;
const { data, error } = await supabase.from('hackathons').insert([
{ title, description, start_date, max_team_size, type, url, created_by_user_id: decoded.id, organizer_name: user.name }
]).select();
if (error) return res.status(500).json({ error: error.message });
res.json({ id: data[0].id });
} catch (err) {
return res.status(401).json({ error: 'Unauthorized' });
}
});
// Get Single Hackathon Details
app.get('/api/hackathons/:id', async (req, res) => {
const { data, error } = await supabase.from('hackathons').select('*').eq('id', req.params.id).single();
if (error) return res.status(500).json({ error: error.message });
res.json(data);
});
// Delete Hackathon
app.delete('/api/hackathons/:id', async (req, res) => {
const token = req.headers.authorization?.split(' ')[1];
if (!token) return res.status(401).json({ error: 'Unauthorized' });
try {
const decoded = jwt.verify(token, SECRET_KEY);
// Verify ownership
const { data: hackathon } = await supabase.from('hackathons').select('created_by_user_id').eq('id', req.params.id).single();
if (!hackathon) return res.status(404).json({ error: 'Hackathon not found' });
// Ensure user is the creator
if (hackathon.created_by_user_id !== decoded.id) {
return res.status(403).json({ error: 'Only the creator can delete this hackathon' });
}
// Delete teams and requests first (if no Cascade)
// Ideally DB has ON DELETE CASCADE, but to be safe:
// 1. Get all team IDs
const { data: teams } = await supabase.from('teams').select('id').eq('hackathon_id', req.params.id);
const teamIds = teams.map(t => t.id);
if (teamIds.length > 0) {
// Delete requests for these teams
await supabase.from('requests').delete().in('team_id', teamIds);
// Delete teams
await supabase.from('teams').delete().eq('hackathon_id', req.params.id);
}
// Delete Hackathon
const { error } = await supabase.from('hackathons').delete().eq('id', req.params.id);
if (error) return res.status(500).json({ error: error.message });
res.json({ message: 'Hackathon deleted successfully' });
} catch (err) {
console.error(err);
return res.status(401).json({ error: 'Unauthorized or server error' });
}
});
// --- Team Routes ---
// Get Teams for a Hackathon
app.get('/api/hackathons/:id/teams', async (req, res) => {
const token = req.headers.authorization?.split(' ')[1];
let userId = null;
if (token) {
try {
const decoded = jwt.verify(token, SECRET_KEY);
userId = decoded.id;
} catch (e) {
// Ignore invalid token, just treat as guest
}
}
const { data: teams, error } = await supabase
.from('teams')
.select(`
*,
leader:users!leader_id (name, email),
requests (
status,
user_id,
user:users (name)
)
`)
.eq('hackathon_id', req.params.id);
if (error) return res.status(500).json({ error: error.message });
// Format the response
const formattedTeams = teams.map(team => {
const approvedRequests = team.requests ? team.requests.filter(r => r.status === 'approved') : [];
const memberNames = approvedRequests.map(r => r.user?.name).filter(Boolean).join(',');
// Determine user status if logged in
let userStatus = null;
if (userId) {
const userRequest = team.requests ? team.requests.find(r => r.user_id === userId) : null;
if (userRequest) {
userStatus = userRequest.status;
} else if (team.leader_id === userId) {
userStatus = 'leader';
}
}
return {
...team,
leader_name: team.leader?.name,
leader_email: team.leader?.email,
current_members: approvedRequests.length,
member_names: memberNames,
user_status: userStatus
};
});
res.json(formattedTeams);
});
// Create Team
app.post('/api/hackathons/:id/teams', async (req, res) => {
const token = req.headers.authorization?.split(' ')[1];
if (!token) return res.status(401).json({ error: 'Unauthorized' });
try {
const decoded = jwt.verify(token, SECRET_KEY);
const { name, description, needed_skills } = req.body;
const skillsString = Array.isArray(needed_skills) ? needed_skills.join(',') : needed_skills;
// Insert team
const { data: teamData, error: teamError } = await supabase.from('teams').insert([
{ name, hackathon_id: req.params.id, leader_id: decoded.id, description, needed_skills: skillsString }
]).select();
if (teamError) return res.status(500).json({ error: teamError.message });
const teamId = teamData[0].id;
// Auto-add leader as member (approved)
const { error: reqError } = await supabase.from('requests').insert([
{ team_id: teamId, user_id: decoded.id, status: 'approved' }
]);
if (reqError) console.error("Failed to add leader to team members", reqError);
res.json({ id: teamId });
} catch (err) {
return res.status(401).json({ error: 'Unauthorized' });
}
});
// Join Team Request
app.post('/api/teams/:id/join', async (req, res) => {
const token = req.headers.authorization?.split(' ')[1];
if (!token) return res.status(401).json({ error: 'Unauthorized' });
try {
const decoded = jwt.verify(token, SECRET_KEY);
// Check if already requested
const { data: existing } = await supabase.from('requests')
.select('*')
.eq('team_id', req.params.id)
.eq('user_id', decoded.id)
.single();
if (existing) return res.status(400).json({ error: 'Request already sent' });
const { error } = await supabase.from('requests').insert([
{ team_id: req.params.id, user_id: decoded.id, status: 'pending' }
]);
if (error) return res.status(500).json({ error: error.message });
res.json({ message: 'Request sent' });
} catch (err) {
return res.status(401).json({ error: 'Unauthorized' });
}
});
// Get Requests for a Team
app.get('/api/teams/:id/requests', async (req, res) => {
const { data: requests, error } = await supabase
.from('requests')
.select(`
id, status, user_id,
user:users (name, email, university, skills)
`)
.eq('team_id', req.params.id);
if (error) return res.status(500).json({ error: error.message });
const formattedRequests = requests.map(r => ({
id: r.id,
user_id: r.user_id,
status: r.status,
user_name: r.user?.name,
user_email: r.user?.email,
user_university: r.user?.university,
user_skills: r.user?.skills ? r.user.skills.split(',') : []
}));
res.json(formattedRequests);
});
// Approve/Reject Request
app.put('/api/teams/:id/requests/:requestId', async (req, res) => {
const { status, rejection_reason } = req.body;
const { error } = await supabase
.from('requests')
.update({ status, rejection_reason: status === 'rejected' ? rejection_reason : null })
.eq('id', req.params.requestId);
if (error) return res.status(500).json({ error: error.message });
res.json({ message: 'Status updated' });
});
// Edit Team
app.put('/api/teams/:id', async (req, res) => {
const token = req.headers.authorization?.split(' ')[1];
if (!token) return res.status(401).json({ error: 'Unauthorized' });
try {
const decoded = jwt.verify(token, SECRET_KEY);
const { name, description, needed_skills } = req.body;
const skillsString = Array.isArray(needed_skills) ? needed_skills.join(',') : needed_skills;
// Verify ownership
const { data: team } = await supabase.from('teams').select('leader_id').eq('id', req.params.id).single();
if (!team) return res.status(404).json({ error: 'Team not found' });
if (team.leader_id !== decoded.id) return res.status(403).json({ error: 'Only the leader can edit the team' });
const { error } = await supabase
.from('teams')
.update({ name, description, needed_skills: skillsString })
.eq('id', req.params.id);
if (error) return res.status(500).json({ error: error.message });
res.json({ message: 'Team updated' });
} catch (err) {
return res.status(401).json({ error: 'Unauthorized' });
}
});
// Delete Team
app.delete('/api/teams/:id', async (req, res) => {
const token = req.headers.authorization?.split(' ')[1];
if (!token) return res.status(401).json({ error: 'Unauthorized' });
try {
const decoded = jwt.verify(token, SECRET_KEY);
// Verify ownership
const { data: team } = await supabase.from('teams').select('leader_id').eq('id', req.params.id).single();
if (!team) return res.status(404).json({ error: 'Team not found' });
if (team.leader_id !== decoded.id) return res.status(403).json({ error: 'Only the leader can delete the team' });
// Delete requests first (though Cascade might handle it if set up in DB, explicit is safer here if unsure)
await supabase.from('requests').delete().eq('team_id', req.params.id);
const { error } = await supabase.from('teams').delete().eq('id', req.params.id);
if (error) return res.status(500).json({ error: error.message });
res.json({ message: 'Team deleted' });
} catch (err) {
return res.status(401).json({ error: 'Unauthorized' });
}
});
app.get(/.*/, (req, res) => {
res.sendFile(path.join(__dirname, 'client/dist', 'index.html'));
});
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});