forked from pointblank-club/pbctf
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathroute.ts
More file actions
490 lines (453 loc) · 14.6 KB
/
Copy pathroute.ts
File metadata and controls
490 lines (453 loc) · 14.6 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
import { NextResponse } from "next/server";
import { auth } from "@/Firebase";
import {
createUserWithEmailAndPassword,
sendEmailVerification,
} from "firebase/auth";
import { cloudinaryV2 } from "@/c";
import dbConnect from "@/lib/db";
import User, { IUser } from "@/models/User";
import { verifyRecaptcha } from "@/lib/recaptcha";
import { checkRateLimit, getClientIp } from "@/lib/rate-limit";
import { getAuth as getAdminAuth } from "@/lib/firebase-admin";
import { isRegistrationClosed } from "@/lib/constants";
// Configure route
export const dynamic = "force-dynamic";
export const runtime = "nodejs";
// Configure Cloudinary
cloudinaryV2.config({
cloud_name: process.env.CLOUDINARY_CLOUD_NAME,
api_key: process.env.CLOUDINARY_API_KEY,
api_secret: process.env.CLOUDINARY_API_SECRET,
});
// Validation functions
const validateEmail = (email: string) =>
/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
const validateDiscordUsername = (username: string) =>
username.length >= 2 && username.length <= 32;
const validatePhone = (phone: string) => /^\+?\d{1,4}[-\s]?\d{10}$/.test(phone);
const validateAge = (age: number) => age >= 13 && age <= 100;
const validatePassword = (password: string) => {
if (password.length < 8) return false;
if (!/[A-Z]/.test(password)) return false;
if (!/[a-z]/.test(password)) return false;
if (!/[0-9]/.test(password)) return false;
if (!/[^A-Za-z0-9]/.test(password)) return false;
return true;
};
const validateURL = (url: string) => {
try {
new URL(url);
return true;
} catch {
return false;
}
};
// Upload base64 file to Cloudinary
async function uploadBase64ToCloudinary(
base64Data: string,
folder: string,
resourceType: "image" | "raw",
): Promise<string> {
return new Promise((resolve, reject) => {
cloudinaryV2.uploader.upload(
base64Data,
{
folder,
resource_type: resourceType,
},
(error, result) => {
if (error) reject(error);
else resolve(result!.secure_url);
},
);
});
}
export async function POST(request: Request) {
try {
// IP rate limiting (5 requests per minute)
const ip = getClientIp(request);
if (!(await checkRateLimit(ip, 5, 60 * 1000))) {
return NextResponse.json(
{
success: false,
message: "Too many requests. Please try again later.",
error: {
code: "rate_limit_exceeded",
message: "Rate limit exceeded",
},
},
{ status: 429 },
);
}
if (isRegistrationClosed()) {
return NextResponse.json(
{
success: false,
message:
"Registration deadline has passed. Registrations are no longer accepted.",
error: {
code: "registration_closed",
message:
"Registration deadline has passed. Registrations are no longer accepted.",
},
},
{ status: 403 },
);
}
const formData = await request.formData();
// reCAPTCHA v3 background score check — reject likely-bot registrations
// before doing any Firebase/Cloudinary/DB work.
const recaptchaToken = formData.get("recaptcha_token") as string | null;
const captcha = await verifyRecaptcha(recaptchaToken, "register");
if (!captcha.ok) {
console.warn(
"[register] reCAPTCHA rejected:",
captcha.reason,
captcha.score,
);
return NextResponse.json(
{
success: false,
message: "Security check failed. Please try again.",
error: {
code: "recaptcha_failed",
message: "reCAPTCHA verification failed",
},
},
{ status: 400 },
);
}
const isGoogle = formData.get("auth_provider") === "google";
let googleUid: string | undefined;
let googleEmail: string | undefined;
if (isGoogle) {
const idToken = formData.get("id_token") as string | null;
if (!idToken) {
return NextResponse.json(
{
success: false,
message: "Missing Google sign-in token",
error: {
code: "missing_id_token",
message: "Missing Google sign-in token",
},
},
{ status: 400 },
);
}
try {
const decoded = await getAdminAuth().verifyIdToken(idToken);
googleUid = decoded.uid;
googleEmail = decoded.email?.toLowerCase();
} catch (tokenError) {
console.error(
"[register] Google ID token verification failed:",
tokenError,
);
return NextResponse.json(
{
success: false,
message: "Invalid Google sign-in token. Please sign in again.",
error: {
code: "invalid_id_token",
message: "Invalid Google sign-in token",
},
},
{ status: 401 },
);
}
if (!googleEmail) {
return NextResponse.json(
{
success: false,
message: "Your Google account has no email address.",
error: {
code: "google_no_email",
message: "Google account has no email address",
},
},
{ status: 400 },
);
}
}
// Helper to convert File to base64
const fileToBase64 = async (file: File): Promise<string> => {
const arrayBuffer = await file.arrayBuffer();
const buffer = Buffer.from(arrayBuffer);
return `data:${file.type};base64,${buffer.toString("base64")}`;
};
// Extract fields
const name = formData.get("name") as string;
// For Google, the email comes from the verified ID token, never the client.
const email = isGoogle
? (googleEmail as string)
: (formData.get("email") as string);
const password = formData.get("password") as string;
const discord_username = formData.get("discord_username") as string;
const phone = formData.get("phone") as string;
const age = formData.get("age") as string;
const organisation = formData.get("organisation") as string;
const bio = formData.get("bio") as string;
// Handle files
const resumeFile = formData.get("resume") as File | null;
const profilePicFile = formData.get("profile_picture") as File | null;
let resume: string | undefined;
if (resumeFile && resumeFile.size > 0) {
resume = await fileToBase64(resumeFile);
}
let profile_picture: string | undefined;
if (profilePicFile && profilePicFile.size > 0) {
profile_picture = await fileToBase64(profilePicFile);
}
const github_link = formData.get("github_link") as string;
const linkedin_link = formData.get("linkedin_link") as string;
const portfolio_link = formData.get("portfolio_link") as string;
const ctf_profile = formData.get("ctf_profile") as string;
const isLooking = formData.get("isLooking") === "true";
const attendedZenith = formData.get("attended_zenith") === "true";
const attendedPBCTF4 = formData.get("attended_pbctf4") === "true";
// Validation
const errors: Record<string, string> = {};
if (!name?.trim() || name.length < 2 || name.length > 100) {
errors.name = "Name is required (2-100 characters)";
}
if (!email?.trim()) {
errors.email = "Email is required";
} else if (!validateEmail(email)) {
errors.email = "Invalid email format";
}
// Google users have no password — Firebase handles their credential.
if (!isGoogle && (!password || !validatePassword(password))) {
errors.password =
"Password must be at least 8 characters and contain uppercase, lowercase, number, and special character";
}
if (!discord_username?.trim()) {
errors.discord_username = "Discord username is required";
} else if (!validateDiscordUsername(discord_username)) {
errors.discord_username = "Invalid Discord username";
}
if (!phone?.trim()) {
errors.phone = "Phone number is required";
} else if (!validatePhone(phone)) {
errors.phone = "Invalid phone format";
}
if (age === undefined || age === null) {
errors.age = "Age is required";
} else if (!validateAge(Number(age))) {
errors.age = "Age must be between 13 and 100";
}
if (
!organisation?.trim() ||
organisation.length < 2 ||
organisation.length > 200
) {
errors.organisation = "Organisation is required (2-200 characters)";
}
// Optional URL validations
if (github_link && !validateURL(github_link)) {
errors.github_link = "Invalid GitHub URL";
}
if (linkedin_link && !validateURL(linkedin_link)) {
errors.linkedin_link = "Invalid LinkedIn URL";
}
if (portfolio_link && !validateURL(portfolio_link)) {
errors.portfolio_link = "Invalid portfolio URL";
}
if (ctf_profile && !validateURL(ctf_profile)) {
errors.ctf_profile = "Invalid CTF profile URL";
}
if (Object.keys(errors).length > 0) {
console.error("Registration validation errors:", errors);
return NextResponse.json(
{
success: false,
message: "Validation error",
errors,
},
{ status: 400 },
);
}
// Connect to database
await dbConnect();
// Check if email already exists
const existingUser = await User.findOne({ email: email.toLowerCase() });
if (existingUser) {
return NextResponse.json(
{
success: false,
message: "Email already exists",
error: { code: "email_exists", message: "Email already exists" },
},
{ status: 409 },
);
}
// Check if discord username already exists
const existingDiscord = await User.findOne({ discord_username });
if (existingDiscord) {
return NextResponse.json(
{
success: false,
message: "Discord username already exists",
error: {
code: "discord_exists",
message: "Discord username already exists",
},
},
{ status: 409 },
);
}
// Check if phone already exists
const existingPhone = await User.findOne({ phone });
if (existingPhone) {
return NextResponse.json(
{
success: false,
message: "Phone number already exists",
error: {
code: "phone_exists",
message: "Phone number already exists",
},
},
{ status: 409 },
);
}
if (isGoogle) {
const existingUid = await User.findOne({ uid: googleUid });
if (existingUid) {
return NextResponse.json(
{
success: false,
message:
"This Google account is already registered. Please log in.",
error: {
code: "already_registered",
message: "Account already exists",
},
},
{ status: 409 },
);
}
}
// Resolve the Firebase uid. Email/password users are created here (and sent
// a verification email); Google users already exist in Firebase with a
// verified email, so we reuse the uid from their ID token and skip both.
let uid: string;
if (isGoogle) {
uid = googleUid!;
} else {
try {
const userCredential = await createUserWithEmailAndPassword(
auth,
email,
password,
);
await sendEmailVerification(userCredential.user);
uid = userCredential.user.uid;
} catch (firebaseError: any) {
if (firebaseError.code === "auth/email-already-in-use") {
return NextResponse.json(
{
success: false,
message: "Email already exists",
error: { code: "email_exists", message: "Email already exists" },
},
{ status: 409 },
);
}
if (firebaseError.code === "auth/weak-password") {
return NextResponse.json(
{
success: false,
message: "Password is too weak",
error: { code: "weak_password", message: "Password is too weak" },
},
{ status: 400 },
);
}
throw firebaseError;
}
}
// Upload files to Cloudinary if provided
let resumeUrl: string | undefined;
let profilePicUrl: string | undefined;
if (resume) {
try {
resumeUrl = await uploadBase64ToCloudinary(
resume,
"zenith/resumes",
"raw",
);
} catch (uploadError) {
console.error("Resume upload error:", uploadError);
// Continue without resume
}
}
if (profile_picture) {
try {
profilePicUrl = await uploadBase64ToCloudinary(
profile_picture,
"zenith/profiles",
"image",
);
} catch (uploadError) {
console.error("Profile picture upload error:", uploadError);
// Continue without profile picture
}
}
// Create user in MongoDB
const newUser = new User({
uid,
name: name.trim(),
email: email.toLowerCase().trim(),
phone: phone.trim(),
discord_username: discord_username.trim(),
age: Number(age),
organisation: organisation.trim(),
bio: bio?.trim(),
resume_link: resumeUrl,
profile_picture: profilePicUrl,
github_link: github_link?.trim(),
linkedin_link: linkedin_link?.trim(),
portfolio_link: portfolio_link?.trim(),
ctf_profile: ctf_profile?.trim(),
isLooking: Boolean(isLooking),
attendedZenith: Boolean(attendedZenith),
attendedPBCTF4: Boolean(attendedPBCTF4),
role: "user",
teamCode: undefined,
authProvider: isGoogle ? "google" : "password",
});
await newUser.save();
return NextResponse.json(
{
message: "Registration successful",
uid,
// Google emails arrive verified, so there's nothing pending for them.
status: isGoogle ? "active" : "pending_verification",
user: {
uid,
email: newUser.email,
name: newUser.name,
isAdmin: false,
profile_picture: newUser.profile_picture || null,
},
},
{ status: 201 },
);
} catch (error: any) {
console.error("Registration error:", error);
return NextResponse.json(
{
success: false,
message: error instanceof Error ? error.message : "Server error",
error: {
code: "server_error",
message: error instanceof Error ? error.message : "Server error",
details: process.env.NODE_ENV === "development" ? error : undefined,
},
},
{ status: 500 },
);
}
}