-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
1519 lines (1338 loc) · 56.8 KB
/
Copy pathserver.js
File metadata and controls
1519 lines (1338 loc) · 56.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
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import 'dotenv/config';
import express from 'express';
import cors from 'cors';
import jwt from 'jsonwebtoken';
import nodemailer from 'nodemailer';
import crypto from 'crypto';
import path from 'path';
import fs from 'fs';
import { fileURLToPath } from 'url';
import cookieParser from 'cookie-parser';
import prisma from './prismaClient.js';
import recruitmentRouter from './routes/recruitment/index.js';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const passwordResetTokens = new Map();
const resetRequestTimestamps = new Map();
const DB_PATH = path.join(__dirname, 'database.json');
let memoryDb = { recruitmentApplications: [], projects: [], users: [], allowedEmails: [] };
try {
if (fs.existsSync(DB_PATH)) {
memoryDb = JSON.parse(fs.readFileSync(DB_PATH, 'utf8'));
}
} catch (e) {
console.warn('[DB Notice] Could not parse database.json:', e.message);
}
if (!Array.isArray(memoryDb.recruitmentApplications)) memoryDb.recruitmentApplications = [];
if (!Array.isArray(memoryDb.projects)) memoryDb.projects = [];
if (!Array.isArray(memoryDb.users)) memoryDb.users = [];
if (!Array.isArray(memoryDb.allowedEmails)) memoryDb.allowedEmails = [];
function saveMemoryDb() {
try {
fs.writeFileSync(DB_PATH, JSON.stringify(memoryDb, null, 2), 'utf8');
} catch (e) {
console.warn('[DB Notice] Could not save database.json:', e.message);
}
}
// Database Connection Status Checker
let isPrismaAvailable = false;
async function initDb() {
try {
await prisma.$queryRaw`SELECT 1`;
isPrismaAvailable = true;
console.log('🐘 PostgreSQL Database connected.');
} catch (e) {
isPrismaAvailable = false;
console.log('📁 Local Database: Using database.json (Standalone Local Mode)');
}
}
initDb();
const smtpUser = process.env.SMTP_USER || 'khandelwalprachi42@gmail.com';
const smtpPass = process.env.SMTP_PASS || '';
const FRONTEND_URL = (process.env.FRONTEND_URL || 'http://localhost:5173').replace(/\/$/, '');
const transporter = nodemailer.createTransport({
host: 'smtp.gmail.com',
port: 465,
secure: true,
debug: false,
logger: false,
auth: {
user: smtpUser,
pass: smtpPass
}
});
const JWT_SECRET = process.env.JWT_SECRET || 'HACKCLUB_VIT_SECRET_SESSION_TOKEN_KEY_2026';
const app = express();
app.set('trust proxy', 1);
const defaultAllowedOrigins = [
'http://localhost:3000',
'http://localhost:5173',
'https://recruitment.hackclubvit.co',
'https://hackclubvit.co',
'https://recruitment-platform.hackclubvit.co',
'https://hackclubvit.github.io',
];
const allowedOrigins = process.env.ALLOWED_ORIGIN
? process.env.ALLOWED_ORIGIN.split(',').map(s => s.trim())
: defaultAllowedOrigins;
if (process.env.FRONTEND_URL) {
const cleanFrontend = process.env.FRONTEND_URL.replace(/\/$/, '');
if (!allowedOrigins.includes(cleanFrontend)) {
allowedOrigins.push(cleanFrontend);
}
}
app.use(cors({
origin: function (origin, callback) {
if (!origin || allowedOrigins.includes(origin) || (origin && origin.endsWith('.github.io')) || process.env.NODE_ENV !== 'production') {
callback(null, true);
} else {
callback(null, true);
}
},
credentials: true,
allowedHeaders: ['Content-Type', 'Authorization', 'X-Requested-With', 'Accept'],
methods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS'],
}));
app.use(cookieParser());
app.use(express.json());
// Recruitment Platform API Router
app.use('/api', recruitmentRouter);
/* ------------------------------------------------------------------ */
/* Collection (key/value) helpers */
/* ------------------------------------------------------------------ */
const COLLECTION_KEYS = [
'announcements', 'uploads', 'recentActivities', 'eventsList',
'teamUpdates', 'feedbacks', 'systemStatus', 'weeklyWinners',
'monthlyWinners', 'profile', 'contributions'
];
async function getCollection(name, fallback = []) {
if (isPrismaAvailable) {
try {
const row = await prisma.collection.findUnique({ where: { name } });
if (row && row.data) return row.data;
} catch (err) {}
}
if (memoryDb[name] !== undefined) return memoryDb[name];
return fallback;
}
async function setCollection(name, data) {
if (isPrismaAvailable) {
try {
await prisma.collection.upsert({
where: { name },
update: { data },
create: { name, data }
});
} catch (err) {}
}
memoryDb[name] = data;
saveMemoryDb();
return data;
}
/* ------------------------------------------------------------------ */
/* Row mappers (sanitize incoming payloads to known columns) */
/* ------------------------------------------------------------------ */
const toBig = (v) => BigInt(typeof v === 'string' ? v.replace(/[^0-9]/g, '') || Date.now() : Math.round(v));
function mapUser(u) {
return {
id: toBig(u.id ?? Date.now()),
name: u.name ?? 'Member',
email: u.email ?? null,
password: u.password ?? null,
role: u.role ?? 'Member',
department: u.department ?? null,
status: u.status ?? 'Active',
isReviewer: !!u.isReviewer,
isRecruitmentAdmin: !!u.isRecruitmentAdmin,
permissions: Array.isArray(u.permissions) ? u.permissions : [],
projectsUploaded: Number(u.projectsUploaded ?? 0),
averageRating: String(u.averageRating ?? '0.0'),
badges: u.badges ?? [],
recentProjects: u.recentProjects ?? [],
projectRatingScore: Number(u.projectRatingScore ?? 0),
contributionScore: Number(u.contributionScore ?? 10),
eventScore: Number(u.eventScore ?? 5),
totalScore: Number(u.totalScore ?? 7),
registerNumber: u.registerNumber ?? null,
phoneNumber: u.phoneNumber ?? null,
location: u.location ?? null,
joined: u.joined ?? null,
github: u.github ?? null,
portfolio: u.portfolio ?? null,
avatar: u.avatar ?? null
};
}
function mapProject(p) {
return {
id: toBig(p.id ?? Date.now()),
title: p.title ?? 'Untitled',
description: p.description ?? null,
category: p.category ?? 'Web Development',
problemStatement: p.problemStatement ?? null,
solution: p.solution ?? null,
screenshots: p.screenshots ?? [],
demoVideoUrl: p.demoVideoUrl ?? null,
github: p.github ?? null,
deployment: p.deployment ?? null,
status: p.status ?? 'PENDING_REVIEW',
owner: p.owner ?? null,
rating: String(p.rating ?? '0.0'),
ratingCount: Number(p.ratingCount ?? (Array.isArray(p.individualRatings) ? p.individualRatings.length : 0)),
contributors: p.contributors ?? null,
submissionDate: p.submissionDate ?? null,
technologiesUsed: p.technologiesUsed ?? [],
awards: p.awards ?? [],
individualRatings: p.individualRatings ?? []
};
}
/* ------------------------------------------------------------------ */
/* Validation */
/* ------------------------------------------------------------------ */
function validatePassword(p) {
if (p.length < 8) return "Password must be at least 8 characters.";
if (!/[A-Z]/.test(p)) return "Password must have at least 1 uppercase letter.";
if (!/[a-z]/.test(p)) return "Password must have at least 1 lowercase letter.";
if (!/[0-9]/.test(p)) return "Password must have at least 1 digit.";
if (!/[^A-Za-z0-9]/.test(p)) return "Password must have at least 1 special character.";
if (/([a-zA-Z0-9])\1/.test(p)) return "No identical consecutive alphabets or numbers allowed (e.g., 'aa', '11').";
for (let i = 0; i < p.length - 1; i++) {
let c1 = p.charCodeAt(i);
let c2 = p.charCodeAt(i + 1);
if (c1 >= 48 && c1 <= 57 && c2 === c1 + 1) return "No sequential numbers allowed (e.g., '12').";
if (c1 >= 97 && c1 <= 122 && c2 === c1 + 1) return "No sequential alphabets allowed (e.g., 'ab').";
if (c1 >= 65 && c1 <= 90 && c2 === c1 + 1) return "No sequential alphabets allowed (e.g., 'AB').";
}
return null;
}
function validateEmail(email) {
if (!email || typeof email !== 'string') return false;
const re = /^[^@\s]+@[^@\s]+\.[^@\s]+$/;
return re.test(email.trim());
}
async function findUserByEmail(email) {
if (!email) return null;
try {
const user = await prisma.user.findUnique({ where: { email } });
if (user) return user;
} catch (err) {}
if (Array.isArray(memoryDb.users)) {
const memUser = memoryDb.users.find(u => u.email && u.email.toLowerCase() === email.toLowerCase());
if (memUser) return memUser;
}
return null;
}
// Never send the password column to the client.
function stripPassword(user) {
if (!user) return user;
// eslint-disable-next-line no-unused-vars
const { password, ...safe } = user;
return safe;
}
const stripPasswords = (users) => users.map(stripPassword);
async function isEmailAllowed(email) {
if (!email) return false;
const lower = email.toLowerCase();
// Demo accounts and test admin are always permitted.
if (lower === 'admin@vitstudent.ac.in' || lower === 'user@vitstudent.ac.in' || lower === 'khandelwalprachi42@gmail.com') {
return true;
}
try {
const entry = await prisma.allowedEmail.findUnique({ where: { email } });
if (entry) return true;
} catch (err) {}
if (Array.isArray(memoryDb.allowedEmails)) {
if (memoryDb.allowedEmails.some(e => typeof e === 'string' ? e.toLowerCase() === lower : e.email?.toLowerCase() === lower)) {
return true;
}
}
return validateEmail(email);
}
/* ------------------------------------------------------------------ */
/* Auth middleware */
/* ------------------------------------------------------------------ */
function authenticateToken(req, res, next) {
const authHeader = req.headers['authorization'];
const token = authHeader && authHeader.split(' ')[1];
if (!token) return res.status(401).json({ error: 'Access token required.' });
jwt.verify(token, JWT_SECRET, (err, user) => {
if (err) return res.status(403).json({ error: 'Invalid or expired session token.' });
req.user = user;
next();
});
}
function requireAdmin(req, res, next) {
const role = (req.user?.role || '').toLowerCase();
if (role !== 'admin' && !ADMIN_TIER_ROLES.includes(role)) {
return res.status(403).json({ error: 'Forbidden: Admin access only.' });
}
next();
}
function requireRecruitmentAccess(req, res, next) {
const userRole = (req.user?.role || '').toLowerCase();
const isOverallAdmin = userRole === 'admin' || ADMIN_TIER_ROLES.includes(userRole);
const hasRecruitmentPermission = req.user?.isRecruitmentAdmin === true ||
(Array.isArray(req.user?.permissions) && req.user.permissions.includes('recruitment-admin')) ||
userRole === 'recruitment admin';
if (!isOverallAdmin && !hasRecruitmentPermission) {
return res.status(403).json({
error: 'Forbidden: Recruitment monitoring privileges required. Only overall admins and members granted recruitment-admin access can view this.'
});
}
next();
}
function resolveDisplayName(email, dbUser) {
if (dbUser?.name) return dbUser.name;
let emailPrefix = email.split('@')[0];
let nameParts = emailPrefix.replace(/[0-9]/g, '').split('.').filter(Boolean);
return nameParts.map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join(' ') || 'Member';
}
// Roles that share the full Admin portal. Vice Chairperson, Secretary and
// Co Secretary are treated exactly like Admin; leads + members log in as 'user'.
const ADMIN_TIER_ROLES = ['admin', 'vice chairperson', 'secretary', 'co secretary'];
function resolveRole(email, dbUser, requested) {
if (email === 'admin@vitstudent.ac.in') return 'admin';
if (email === 'user@vitstudent.ac.in') return 'user';
if (dbUser) return ADMIN_TIER_ROLES.includes((dbUser.role || '').toLowerCase()) ? 'admin' : 'user';
return requested || 'user';
}
/* ------------------------------------------------------------------ */
/* Password Reset Token Helpers */
/* ------------------------------------------------------------------ */
function generateResetToken() {
// Generate a 32-byte cryptographically secure random token
const rawToken = crypto.randomBytes(32).toString('hex'); // 64-char hex string
const tokenHash = crypto.createHash('sha256').update(rawToken).digest('hex');
return { rawToken, tokenHash };
}
function hashToken(raw) {
return crypto.createHash('sha256').update(raw).digest('hex');
}
/* ------------------------------------------------------------------ */
/* Email Builder */
/* ------------------------------------------------------------------ */
function buildPasswordResetEmail(toEmail, resetCode) {
return {
from: `"HackClub VIT Chennai" <${smtpUser}>`,
to: toEmail,
replyTo: smtpUser,
subject: 'Your Password Reset Code',
headers: {
'X-Mailer': 'HackClub-VIT-Mailer/1.0',
'X-Priority': '3',
'Importance': 'Normal'
},
text: [
'HackClub VIT Chennai — Password Reset Request',
'',
'We received a request to reset the password for your HackClub VIT Chennai account.',
'',
`Your password reset code is: ${resetCode}`,
'',
'Enter this code on the password reset page to set a new password.',
'This code will expire in 10 minutes.',
'',
'If you did not request a password reset, you can safely ignore this email.',
'Your password will remain unchanged.',
'',
'---',
'HackClub VIT Chennai',
'https://hackclubvit.in'
].join('\n'),
html: `
<div style="font-family: Arial, sans-serif; max-width: 520px; margin: auto; padding: 0; border: 1px solid #dddddd; border-radius: 8px; overflow: hidden;">
<div style="background-color: #ec3750; padding: 24px; text-align: center;">
<h1 style="color: #ffffff; margin: 0; font-size: 22px; font-weight: bold; letter-spacing: 0.5px;">HackClub VIT Chennai</h1>
</div>
<div style="background-color: #ffffff; padding: 32px;">
<h2 style="color: #1a1a1a; font-size: 20px; margin-top: 0; margin-bottom: 12px;">Password Reset Code</h2>
<p style="font-size: 15px; color: #444444; line-height: 1.7; margin-bottom: 8px;">
We received a request to reset the password for your <strong>HackClub VIT Chennai</strong> account.
</p>
<p style="font-size: 15px; color: #444444; line-height: 1.7; margin-bottom: 28px;">
Your 6-digit password reset code is:
</p>
<div style="text-align: center; margin: 28px 0; background-color: #f8f9fa; border: 1px solid #eeeeee; border-radius: 8px; padding: 16px;">
<span style="font-size: 32px; font-weight: bold; letter-spacing: 4px; color: #ec3750; font-family: monospace;">
${resetCode}
</span>
</div>
<p style="font-size: 13px; color: #888888; line-height: 1.6; text-align: center; margin-bottom: 8px;">
Enter this code on the password reset page. It will expire in <strong>10 minutes</strong>.
</p>
<p style="font-size: 13px; color: #888888; line-height: 1.6; text-align: center;">
If you did not request a password reset, you can safely ignore this email.<br>
Your password will remain unchanged.
</p>
</div>
<div style="background-color: #f7f7f7; padding: 16px; text-align: center; border-top: 1px solid #eeeeee;">
<p style="font-size: 12px; color: #aaaaaa; margin: 0;">
This is an automated email. Please do not reply directly.
</p>
</div>
</div>
`
};
}
/* ================================================================== */
/* AUTH */
/* ================================================================== */
// Password login — verifies the email and password.
app.post('/api/auth/login', async (req, res) => {
const { email, password, role } = req.body;
if (!email || !password) return res.status(400).json({ error: 'Please enter both email and password.' });
if (!validateEmail(email)) {
return res.status(400).json({ error: 'Enter your student email only ending with @vitstudent.ac.in' });
}
const passError = validatePassword(password);
if (passError) return res.status(400).json({ error: passError });
const dbUser = await findUserByEmail(email);
const isDemo = email === 'admin@vitstudent.ac.in' || email === 'user@vitstudent.ac.in';
// Accept user's custom password if set, or default shared club password
const expectedPassword = dbUser?.password || 'Hackclub@2026';
if (password !== expectedPassword && !isDemo) {
return res.status(400).json({ error: 'Invalid email or password.' });
}
const resolvedRole = resolveRole(email, dbUser, role);
const name = resolveDisplayName(email, dbUser);
const isOverallAdmin = resolvedRole === 'admin' || ADMIN_TIER_ROLES.includes((dbUser?.role || '').toLowerCase());
const isRecruitmentAdmin = isOverallAdmin || !!dbUser?.isRecruitmentAdmin ||
(Array.isArray(dbUser?.permissions) && dbUser.permissions.includes('recruitment-admin')) ||
(dbUser?.role || '').toLowerCase() === 'recruitment admin';
const permissions = Array.isArray(dbUser?.permissions) ? dbUser.permissions : (isRecruitmentAdmin ? ['recruitment-admin'] : []);
const tokenPayload = {
name,
email,
role: resolvedRole,
isRecruitmentAdmin,
permissions
};
const token = jwt.sign(tokenPayload, JWT_SECRET, { expiresIn: '7d' });
return res.json({ token, role: resolvedRole, user: tokenPayload });
});
// Signup — gated by the allowlist + email format.
const HACKCLUB_DEPARTMENTS = ['Operations', 'Technical', 'Projects', 'Design & Social Media', 'Finance', 'Research & Development'];
app.post('/api/auth/signup', async (req, res) => {
const { email, password, name, registerNumber, department } = req.body;
if (!email || !password || !name || !registerNumber) return res.status(400).json({ error: 'Please fill in all fields.' });
if (!validateEmail(email)) {
return res.status(400).json({ error: 'Enter your student email only ending with @vitstudent.ac.in' });
}
const regNo = String(registerNumber).trim().toUpperCase();
if (!/^[0-9]{2}[A-Z]{3}[0-9]{4}$/.test(regNo)) {
return res.status(400).json({ error: 'Enter a valid VIT register number (e.g., 24BCE1234).' });
}
const dept = (department || '').trim();
if (dept && !HACKCLUB_DEPARTMENTS.includes(dept)) {
return res.status(400).json({ error: 'Please select a valid HackClub department.' });
}
const allowed = await isEmailAllowed(email);
if (!allowed) {
return res.status(403).json({ error: 'This email is not approved for signup. Please contact a HackClub admin to be added to the allowlist.' });
}
const passError = validatePassword(password);
if (passError) return res.status(400).json({ error: passError });
const existing = await findUserByEmail(email);
if (existing) return res.status(400).json({ error: 'Account with this email already exists.' });
try {
await prisma.user.create({
data: mapUser({
id: Date.now(),
name,
email,
password,
registerNumber: regNo,
department: dept || null,
role: 'Member',
status: 'Active',
badges: ['New Maker'],
contributionScore: 10,
eventScore: 5,
totalScore: 7
})
});
} catch (err) {
console.warn(`[DB Notice] Registration create for ${email}: ${err.message}`);
}
return res.status(201).json({ success: true, message: 'Registration successful. You can now login.' });
});
// Forgot password — generates a 6-digit reset code and emails it to user.
app.post('/api/auth/forgot-password', async (req, res) => {
let { email } = req.body;
if (!email) return res.status(400).json({ error: 'Please enter your email address.' });
email = email.trim().toLowerCase();
if (!validateEmail(email)) {
return res.status(400).json({ error: 'Please enter a valid email address.' });
}
// Rate limiting — one request per 60 seconds per email
const lastRequest = resetRequestTimestamps.get(email);
if (lastRequest && Date.now() - lastRequest < 60 * 1000) {
const remaining = Math.ceil((60 * 1000 - (Date.now() - lastRequest)) / 1000);
return res.status(429).json({
error: `Please wait ${remaining} seconds before requesting another reset code.`
});
}
// Invalidate any existing code for this email before issuing a new one
for (const [code, record] of passwordResetTokens.entries()) {
if (record.email === email) {
passwordResetTokens.delete(code);
}
}
// Generate a 6-digit numeric reset code
const resetCode = String(Math.floor(100000 + Math.random() * 900000));
const expires = Date.now() + 10 * 60 * 1000; // 10 minutes
passwordResetTokens.set(resetCode, { email, expires, used: false });
resetRequestTimestamps.set(email, Date.now());
console.log(`[PASSWORD RESET] Request for: ${email}`);
console.log(`[PASSWORD RESET] Attempting to send email to: ${email}`);
try {
await transporter.sendMail(buildPasswordResetEmail(email, resetCode));
console.log(`[PASSWORD RESET] Email sent successfully to: ${email}`);
return res.json({
success: true,
message: 'If an account exists for this email, a password reset code has been sent.'
});
} catch (err) {
// Clean up the token if email failed — user can try again
passwordResetTokens.delete(resetCode);
resetRequestTimestamps.delete(email);
console.error(`[PASSWORD RESET] Email delivery failed for ${email}: ${err.message}`);
return res.status(500).json({
error: "We couldn't send the password reset email right now. Please try again later."
});
}
});
// Verify reset code (before showing the reset password form)
app.post('/api/auth/verify-reset-code', (req, res) => {
const { resetCode } = req.body;
if (!resetCode) {
return res.status(400).json({ error: 'Reset code is required.' });
}
const record = passwordResetTokens.get(resetCode);
if (!record) {
return res.status(400).json({ error: 'Invalid reset code. Please request a new one.' });
}
if (record.used) {
return res.status(400).json({ error: 'This reset code has already been used. Please request a new one.' });
}
if (Date.now() > record.expires) {
passwordResetTokens.delete(resetCode);
return res.status(400).json({ error: 'This reset code has expired. Please request a new one.' });
}
return res.json({ success: true, message: 'Reset code verified.' });
});
// Reset password — validates the 6-digit reset code and updates the password.
app.post('/api/auth/reset-password', async (req, res) => {
const { resetCode, newPassword } = req.body;
if (!resetCode || !newPassword) {
return res.status(400).json({ error: 'Reset code and new password are required.' });
}
const record = passwordResetTokens.get(resetCode);
if (!record) {
return res.status(400).json({ error: 'Invalid reset code. Please request a new one.' });
}
if (record.used) {
return res.status(400).json({ error: 'This reset code has already been used. Please request a new one.' });
}
if (Date.now() > record.expires) {
passwordResetTokens.delete(resetCode);
return res.status(400).json({ error: 'This reset code has expired. Please request a new one.' });
}
const passError = validatePassword(newPassword);
if (passError) return res.status(400).json({ error: passError });
const { email } = record;
const user = await findUserByEmail(email);
if (!user) {
console.error(`[PASSWORD RESET] No account found for ${email} — password NOT updated.`);
return res.status(500).json({
error: "We couldn't update your password right now. Please try again later or contact an admin."
});
}
try {
await prisma.user.update({ where: { id: user.id }, data: { password: newPassword } });
console.log(`[PASSWORD RESET] Password updated successfully for: ${email}`);
} catch (err) {
console.error(`[PASSWORD RESET] Password update failed for ${email}: ${err.message}`);
return res.status(500).json({
error: "We couldn't update your password right now. Please try again later or contact an admin."
});
}
// Mark code as used (single-use)
record.used = true;
// Also clean up rate limit entry so user can request again if needed
resetRequestTimestamps.delete(email);
return res.json({
success: true,
message: 'Your password has been reset successfully. Please sign in with your new password.'
});
});
app.get('/api/auth/me', authenticateToken, (req, res) => {
res.json({ user: req.user });
});
/* ================================================================== */
/* GLOBAL STATE */
/* ================================================================== */
app.get('/api/data', authenticateToken, async (req, res) => {
let dbUser = await findUserByEmail(req.user.email);
// Create a user record on first login if one doesn't exist yet (demo accounts).
if (!dbUser) {
dbUser = mapUser({
id: Date.now(),
name: req.user.name,
email: req.user.email,
role: req.user.role === 'admin' ? 'Admin' : 'Member',
isReviewer: req.user.role === 'admin',
badges: req.user.role === 'admin' ? ['Lead Organizer'] : ['New Maker'],
contributionScore: 10,
eventScore: 5,
totalScore: 7
});
try {
await prisma.user.create({ data: dbUser });
} catch (err) {
console.warn(`[DB Notice] User create fallback: ${err.message}`);
}
}
let users = [], projects = [], recruitmentApplications = [], allowedEmails = [];
try {
[users, projects, recruitmentApplications, allowedEmails] = await Promise.all([
prisma.user.findMany({ orderBy: { id: 'asc' } }),
prisma.project.findMany({ orderBy: { id: 'desc' } }),
prisma.recruitmentApplication.findMany({ orderBy: { id: 'desc' } }),
prisma.allowedEmail.findMany({ orderBy: { createdAt: 'asc' } })
]);
} catch (err) {
console.warn(`[DB Notice] Data fetch fallback: ${err.message}`);
}
const collections = {};
for (const key of COLLECTION_KEYS) {
try {
collections[key] = await getCollection(key, key === 'weeklyWinners' || key === 'monthlyWinners' || key === 'profile' ? {} : []);
} catch (err) {
collections[key] = key === 'weeklyWinners' || key === 'monthlyWinners' || key === 'profile' ? {} : [];
}
}
const profile = {
name: dbUser.name,
role: dbUser.role,
department: dbUser.department || null,
registerNumber: dbUser.registerNumber || '24BCE' + (Number(dbUser.id % 9000n) + 1000),
email: dbUser.email,
phoneNumber: dbUser.phoneNumber || '+91 98765 ' + (Number(dbUser.id % 90000n) + 10000),
location: dbUser.location || 'Chennai',
joined: dbUser.joined || 'Jun 2026',
github: dbUser.github || `github.com/${(dbUser.email || 'member').split('@')[0]}`,
portfolio: dbUser.portfolio || `${(dbUser.email || 'member').split('@')[0]}.dev`,
badges: dbUser.badges,
isReviewer: dbUser.isReviewer,
avatar: dbUser.avatar || `emoji:👤`
};
const contributions = [
{ label: 'Projects contributed', value: String(dbUser.projectsUploaded) },
{ label: 'Contribution Score', value: String(dbUser.contributionScore) },
{ label: 'Event Score', value: String(dbUser.eventScore) },
{ label: 'Total Performance Score', value: `${dbUser.totalScore} pts` }
];
res.json({
users: stripPasswords(users.length > 0 ? users : (Array.isArray(memoryDb.users) ? memoryDb.users : [])),
projects: projects.length > 0 ? projects : memoryDb.projects,
recruitmentApplications: (recruitmentApplications || []).filter(a => !['24BPS1029', '24BYB1097', '24BCE9999'].includes(a.registerNumber)),
allowedEmails,
...collections,
profile,
contributions
});
});
app.get('/api/public/leaderboard', async (req, res) => {
try {
const users = await prisma.user.findMany();
const sorted = [...users].sort((a, b) => b.totalScore - a.totalScore);
res.json(stripPasswords(sorted));
} catch (err) {
console.warn(`[DB Notice] Public leaderboard fetch fallback: ${err.message}`);
res.json([]);
}
});
/* ================================================================== */
/* PROJECTS */
/* ================================================================== */
app.post('/api/projects', authenticateToken, async (req, res) => {
const {
title, description, category, problemStatement, solution,
screenshots, demoVideoUrl, github, deployment, technologiesUsed, owner
} = req.body;
if (!title || !description) {
return res.status(400).json({ error: 'Project Title and Description are required.' });
}
const newProjectPayload = {
id: Date.now(),
title,
description,
category: category || 'Web Development',
problemStatement: problemStatement || null,
solution: solution || null,
screenshots: Array.isArray(screenshots) ? screenshots : [],
demoVideoUrl: demoVideoUrl || null,
github: github || null,
deployment: deployment || null,
status: 'PENDING_REVIEW',
owner: owner || req.user.name,
rating: '0.0',
ratingCount: 0,
submissionDate: new Date().toISOString().split('T')[0],
technologiesUsed: Array.isArray(technologiesUsed) ? technologiesUsed : ['React', 'CSS'],
individualRatings: [],
awards: []
};
try {
const created = await prisma.project.create({
data: mapProject(newProjectPayload)
});
} catch (err) {
console.warn(`[DB Notice] Project creation error: ${err.message}`);
}
memoryDb.projects.unshift(newProjectPayload);
saveMemoryDb();
const activities = await getCollection('recentActivities', []);
const newActivity = { id: Date.now(), label: 'Submitted project proposal', detail: `"${title}" was submitted for review`, time: 'Just now' };
await setCollection('recentActivities', [newActivity, ...activities].slice(0, 10));
res.status(201).json({ project: newProjectPayload });
});
app.get('/api/projects/leaderboard', async (req, res) => {
let projects = [];
try {
projects = await prisma.project.findMany();
} catch (err) {}
if (!projects || projects.length === 0) {
projects = memoryDb.projects;
}
const sorted = [...projects].sort((a, b) => {
const rA = parseFloat(a.rating) || 0;
const rB = parseFloat(b.rating) || 0;
if (rB !== rA) return rB - rA;
const cA = Number(a.ratingCount || (Array.isArray(a.individualRatings) ? a.individualRatings.length : 0));
const cB = Number(b.ratingCount || (Array.isArray(b.individualRatings) ? b.individualRatings.length : 0));
if (cB !== cA) return cB - cA;
return String(a.submissionDate || '').localeCompare(String(b.submissionDate || ''));
});
res.json(sorted);
});
// Admin rating endpoint (0-10, one rating per admin)
app.post('/api/projects/:id/rate', authenticateToken, requireAdmin, async (req, res) => {
const { id } = req.params;
const { rating, comment } = req.body;
const numericRating = parseFloat(rating);
if (isNaN(numericRating) || numericRating < 0 || numericRating > 10) {
return res.status(400).json({ error: 'Rating must be a valid number between 0 and 10.' });
}
const formattedRating = numericRating.toFixed(1);
const adminName = req.user.name;
let project = null;
try {
project = await prisma.project.findUnique({ where: { id: toBig(id) } });
} catch (err) {}
if (!project) {
project = memoryDb.projects.find(p => String(p.id) === String(id));
}
if (!project) return res.status(404).json({ error: 'Project not found.' });
const individualRatings = Array.isArray(project.individualRatings) ? [...project.individualRatings] : [];
const idx = individualRatings.findIndex((r) => r.user === adminName);
const entry = { user: adminName, rating: numericRating, comment: comment || '' };
if (idx !== -1) {
individualRatings[idx] = entry;
} else {
individualRatings.push(entry);
}
const valid = individualRatings.filter((r) => !isNaN(parseFloat(r.rating)));
const avg = valid.length > 0 ? valid.reduce((s, r) => s + parseFloat(r.rating), 0) / valid.length : 0;
const avgFormatted = avg.toFixed(1);
const newRatingCount = valid.length;
const newStatus = valid.length >= 1 && project.status === 'PENDING_REVIEW' ? 'UNDER_REVIEW' : project.status;
try {
await prisma.project.update({
where: { id: toBig(id) },
data: {
individualRatings,
rating: avgFormatted,
ratingCount: newRatingCount,
status: newStatus
}
});
} catch (err) {
console.warn(`[DB Notice] Project rating update error: ${err.message}`);
}
const memProj = memoryDb.projects.find(p => String(p.id) === String(id));
if (memProj) {
memProj.individualRatings = individualRatings;
memProj.rating = avgFormatted;
memProj.ratingCount = newRatingCount;
memProj.status = newStatus;
saveMemoryDb();
}
const updatedProject = {
...project,
individualRatings,
rating: avgFormatted,
ratingCount: newRatingCount,
status: newStatus
};
const activities = await getCollection('recentActivities', []);
const newActivity = { id: Date.now(), label: 'Reviewed project', detail: `Left evaluation (${formattedRating}/10) on "${project.title}"`, time: 'Just now' };
await setCollection('recentActivities', [newActivity, ...activities].slice(0, 10));
res.json({ success: true, project: updatedProject });
});
/* ================================================================== */
/* USERS (Admin) */
/* ================================================================== */
app.put('/api/users', authenticateToken, async (req, res) => {
const incoming = Array.isArray(req.body) ? req.body : [];
// The client never sees or sends passwords, so preserve existing ones
// (keyed by id) when the admin saves the whole users list.
const existing = await prisma.user.findMany({ select: { id: true, password: true } });
const passwordById = new Map(existing.map((u) => [u.id.toString(), u.password]));
const data = incoming.map((u) => {
const mapped = mapUser(u);
if (mapped.password == null) {
mapped.password = passwordById.get(mapped.id.toString()) ?? null;
}
return mapped;
});
await prisma.$transaction([
prisma.user.deleteMany({}),
prisma.user.createMany({ data })
]);
const users = await prisma.user.findMany({ orderBy: { id: 'asc' } });
res.json({ users: stripPasswords(users) });
});
app.put('/api/users/:id', authenticateToken, async (req, res) => {
const { id } = req.params;
const data = mapUser({ ...req.body, id });
// Don't allow id mutation, and never wipe the password when the client
// (which doesn't hold it) saves a user edit.
delete data.id;
if (data.password == null) delete data.password;
const updated = await prisma.user.update({ where: { id: toBig(id) }, data });
res.json({ user: stripPassword(updated) });
});
app.delete('/api/users/:id', authenticateToken, async (req, res) => {
const { id } = req.params;
await prisma.user.delete({ where: { id: toBig(id) } }).catch(() => {});
const users = await prisma.user.findMany({ orderBy: { id: 'asc' } });
res.json({ users: stripPasswords(users) });
});
/* ================================================================== */
/* COLLECTIONS (bulk wholesale sync) */
/* ================================================================== */
function collectionRoute(path, key) {
app.put(path, authenticateToken, async (req, res) => {
const data = await setCollection(key, req.body);
res.json({ [key]: data });
});
}
collectionRoute('/api/uploads', 'uploads');
collectionRoute('/api/announcements', 'announcements');
collectionRoute('/api/feedbacks', 'feedbacks');
collectionRoute('/api/events', 'eventsList');
collectionRoute('/api/team-updates', 'teamUpdates');
collectionRoute('/api/contributions', 'contributions');
collectionRoute('/api/system-status', 'systemStatus');
collectionRoute('/api/activities', 'recentActivities');
collectionRoute('/api/weekly-winners', 'weeklyWinners');
collectionRoute('/api/monthly-winners', 'monthlyWinners');
app.put('/api/uploads/:id/status', authenticateToken, async (req, res) => {
const { id } = req.params;
const { status } = req.body;
const uploads = await getCollection('uploads', []);
const next = uploads.map((u) => (u.id === parseInt(id, 10) ? { ...u, status } : u));
await setCollection('uploads', next);
res.json({ uploads: next });
});
app.post('/api/announcements', authenticateToken, async (req, res) => {
const { title, body, label } = req.body;
const announcements = await getCollection('announcements', []);
const newAnn = { id: Date.now(), title, body, label: label || 'Info' };
const next = [newAnn, ...announcements];
await setCollection('announcements', next);
res.status(201).json({ announcement: newAnn, announcements: next });
});
app.post('/api/feedback', authenticateToken, async (req, res) => {
const { title, description } = req.body;
const feedbacks = await getCollection('feedbacks', []);
const newFeedback = { id: Date.now(), user: req.user.name, message: description || title, type: 'Bug Report' };
const next = [newFeedback, ...feedbacks];
await setCollection('feedbacks', next);
res.status(201).json({ feedbacks: next });
});
app.put('/api/profile', authenticateToken, async (req, res) => {
const profileUpdate = req.body;
const dbUser = await findUserByEmail(req.user.email);
if (dbUser) {
await prisma.user.update({
where: { id: dbUser.id },
data: {
name: profileUpdate.name || dbUser.name,
phoneNumber: profileUpdate.phoneNumber || dbUser.phoneNumber,
github: profileUpdate.github || dbUser.github,
portfolio: profileUpdate.portfolio || dbUser.portfolio,
avatar: profileUpdate.avatar || dbUser.avatar,