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
508 lines (451 loc) · 13.1 KB
/
Copy pathroute.ts
File metadata and controls
508 lines (451 loc) · 13.1 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
import { NextRequest, NextResponse } from "next/server";
import { cloudinaryV2 } from "@/c";
import fs from "fs";
import path from "path";
import os from "os";
import dbConnect from "@/lib/db";
import User from "@/models/User";
import Team from "@/models/Team";
import {
authenticateUser,
createAuthErrorResponse,
requireAdmin,
requireEmailVerified,
} from "@/lib/middleware/auth";
export const dynamic = "force-dynamic";
export const runtime = "nodejs"; // specify nodejs runtime
export const preferredRegion = "auto"; // or specify regions if needed
// 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,
});
// Function to extract public_id from Cloudinary URL
const extractPublicIdFromUrl = (url: string): string => {
if (!url) return "";
try {
const urlObj = new URL(url);
let pathname = urlObj.pathname;
pathname = pathname.replace(/\/(image|raw)\/upload\//, "");
const publicId = pathname.substring(0, pathname.lastIndexOf("."));
return publicId;
} catch (error) {
console.error("Failed to extract public ID from URL:", error);
return "";
}
};
// Function to delete file from Cloudinary
const deleteFromCloudinary = async (
url: string,
resourceType: string = "image",
): Promise<boolean> => {
if (!url) return true;
const publicId = extractPublicIdFromUrl(url);
if (!publicId) return false;
return new Promise((resolve) => {
cloudinaryV2.uploader.destroy(
publicId,
{ resource_type: resourceType },
(error: Error | null, result: any) => {
if (error || result.result !== "ok") {
console.error("Failed to delete from Cloudinary:", error || result);
resolve(false);
} else {
console.log("Successfully deleted from Cloudinary:", publicId);
resolve(true);
}
},
);
});
};
// Function to upload file to Cloudinary
const uploadToCloudinary = async (
filePath: string,
folder: string,
mimeType: string,
): Promise<string> => {
const resourceType = mimeType.includes("pdf") ? "raw" : "auto";
const uploadOptions: any = {
folder: folder,
resource_type: resourceType,
};
if (mimeType.includes("pdf")) {
uploadOptions.format = "pdf";
uploadOptions.flags = "attachment";
}
return new Promise((resolve, reject) => {
cloudinaryV2.uploader.upload(
filePath,
uploadOptions,
(error: any, result: any) => {
if (error) reject(error);
else {
let url = result?.secure_url || "";
if (mimeType.includes("pdf")) {
if (url.includes("/image/upload/")) {
url = url.replace("/image/upload/", "/raw/upload/");
}
}
resolve(url);
}
try {
fs.unlinkSync(filePath);
} catch (err) {
console.error("Failed to delete temp file:", err);
}
},
);
});
};
// Parse multipart form data
const parseForm = async (
req: Request,
): Promise<{ fields: Record<string, any>; files: Record<string, any> }> => {
const formData = await req.formData();
const fields: Record<string, any> = {};
const files: Record<string, any> = {};
const tempDir = os.tmpdir();
for (const [key, value] of formData.entries()) {
if (value instanceof File) {
const safeFilename = value.name.replace(/[^a-zA-Z0-9.]/g, "_");
const tempFilePath = path.join(tempDir, `${Date.now()}_${safeFilename}`);
const arrayBuffer = await value.arrayBuffer();
await fs.promises.writeFile(tempFilePath, new Uint8Array(arrayBuffer));
files[key] = {
filepath: tempFilePath,
originalFilename: value.name,
mimetype: value.type,
size: value.size,
};
} else {
fields[key] = value;
}
}
return { fields, files };
};
export async function GET(
req: NextRequest,
{ params }: { params: { id: string } },
) {
try {
const authResult = await authenticateUser(req);
if (!authResult.success) {
return createAuthErrorResponse(authResult);
}
await dbConnect();
let user = await User.findOne({ uid: params.id });
if (!user && params.id.includes("@")) {
// Searching by email
user = await User.findOne({ email: params.id });
} else if (!user) {
try {
user = await User.findById(params.id);
} catch (e) {}
}
if (!user) {
return NextResponse.json(
{
message: "User not found",
status: "error",
},
{ status: 404 },
);
}
// A profile is visible when any of these hold:
// - the requester is an admin or evaluator
// - the requester is viewing their own profile
// - the requester and target are on the same team
// - the target is personally "looking for a team" (isLooking)
// - the target's team is discoverable (looking for members)
// Otherwise the profile is private.
const requester = authResult.user;
const isPrivileged =
requester.role === "admin" || requester.role === "evaluator";
const isSelf = requester.uid === user.uid;
const isTeammate =
!!requester.teamCode &&
!!user.teamCode &&
requester.teamCode === user.teamCode;
let canView = user.isLooking || isPrivileged || isSelf || isTeammate;
// Expose members of a team that is itself looking for members, so the team
// can be browsed from the Discover page.
if (!canView && user.teamCode) {
const team = await Team.findOne({ teamCode: user.teamCode }).select(
"isLooking",
);
canView = !!team?.isLooking;
}
if (!canView) {
return NextResponse.json(
{
message: "This profile is private",
status: "error",
},
{ status: 403 },
);
}
return NextResponse.json({
message: "User found",
status: "success",
user: {
uid: user.uid,
email: user.email,
name: user.name,
discord_username: user.discord_username || null,
profile_picture: user.profile_picture || null,
resume_link: user.resume_link || null,
github_link: user.github_link || null,
linkedin_link: user.linkedin_link || null,
portfolio_link: user.portfolio_link || null,
ctf_profile: user.ctf_profile || null,
bio: user.bio || null,
age: user.age || null,
organisation: user.organisation || null,
isLooking: user.isLooking,
role: user.role,
isAdmin: user.role === "admin",
hasSolvedChallenge: user.hasSolvedChallenge || false,
},
});
} catch (error) {
console.error("Error fetching user:", error);
return NextResponse.json(
{
message: "Failed to fetch user",
error: String(error),
status: "error",
},
{ status: 500 },
);
}
}
export async function PUT(
req: NextRequest,
{ params }: { params: { id: string } },
) {
try {
const authResult = await authenticateUser(req);
if (!authResult.success) {
return createAuthErrorResponse(authResult);
}
const { fields, files } = await parseForm(req);
const updates: Record<string, any> = { ...fields };
await dbConnect();
let user = null;
try {
user = await User.findById(params.id);
} catch (e) {
// Ignore invalid ObjectId
}
if (!user) {
// Try finding by uid
user = await User.findOne({ uid: params.id });
}
if (!user) {
return NextResponse.json(
{
message: "User not found",
status: "error",
},
{ status: 404 },
);
}
// Authorization Check
const isSelf = user.uid === authResult.user.uid;
const isAdmin = authResult.user.role === "admin";
if (!isSelf && !isAdmin) {
return NextResponse.json(
{
message: "Unauthorized: You can only update your own profile",
status: "error",
},
{ status: 403 },
);
}
// Check if name update is attempted (not allowed)
if (updates.name) {
return NextResponse.json(
{
message: "Name cannot be updated",
status: "error",
},
{ status: 400 },
);
}
// Handle resume update if provided
if (files.resume) {
const resumeFile = files.resume;
if (!resumeFile.mimetype.includes("pdf")) {
return NextResponse.json(
{
message: "Resume must be in PDF format.",
error: "Invalid resume format",
},
{ status: 400 },
);
}
if (resumeFile.size > 1 * 1024 * 1024) {
return NextResponse.json(
{
message: "Resume file size must be under 1MB.",
error: "File size limit exceeded",
},
{ status: 413 },
);
}
// Delete old resume from Cloudinary if it exists
if (user.resume_link) {
await deleteFromCloudinary(user.resume_link, "raw");
}
// Upload new resume to Cloudinary
try {
const resumeUrl = await uploadToCloudinary(
resumeFile.filepath,
"resumes",
resumeFile.mimetype,
);
updates.resume_link = resumeUrl;
} catch (error) {
console.error("Failed to upload resume:", error);
return NextResponse.json(
{
message: "Failed to upload resume.",
error: String(error),
},
{ status: 500 },
);
}
}
// Handle profile picture update if provided
if (files.profile_picture) {
const profileFile = files.profile_picture;
if (!profileFile.mimetype.includes("image")) {
return NextResponse.json(
{
message: "Profile picture must be an image format.",
error: "Invalid profile picture format",
},
{ status: 400 },
);
}
if (profileFile.size > 1 * 1024 * 1024) {
return NextResponse.json(
{
message: "Profile picture size must be under 1MB.",
error: "File size limit exceeded",
},
{ status: 413 },
);
}
// Delete old profile picture from Cloudinary if it exists
if (user.profile_picture) {
await deleteFromCloudinary(user.profile_picture, "image");
}
// Upload new profile picture to Cloudinary
try {
const profilePictureUrl = await uploadToCloudinary(
profileFile.filepath,
"profile_pictures",
profileFile.mimetype,
);
updates.profile_picture = profilePictureUrl;
} catch (error) {
console.error("Failed to upload profile picture:", error);
return NextResponse.json(
{
message: "Failed to upload profile picture.",
error: String(error),
},
{ status: 500 },
);
}
}
const allowedFields = [
"discord_username",
"bio",
"age",
"organisation",
"resume_link",
"profile_picture",
"github_link",
"linkedin_link",
"portfolio_link",
"ctf_profile",
"isLooking",
];
const updateData: Record<string, any> = {};
for (const field of allowedFields) {
if (updates[field] !== undefined) {
if (field === "age" && updates[field]) {
updateData[field] = parseInt(updates[field]);
} else if (field === "isLooking") {
updateData[field] =
updates[field] === "true" || updates[field] === true;
} else {
updateData[field] = updates[field];
}
}
}
const updatedUser = await User.findByIdAndUpdate(params.id, updateData, {
new: true,
});
return NextResponse.json({
message: "User updated successfully",
id: updatedUser?._id.toString(),
uid: updatedUser?.uid,
status: "success",
});
} catch (error) {
console.error("Error updating user:", error);
return NextResponse.json(
{
message: "Failed to update user",
error: String(error),
status: "error",
},
{ status: 500 },
);
}
}
export async function DELETE(
req: NextRequest,
{ params }: { params: { id: string } },
) {
try {
const authResult = await authenticateUser(req);
if (!authResult.success) {
return createAuthErrorResponse(authResult);
}
const adminError = requireAdmin(authResult);
if (adminError) {
return createAuthErrorResponse(adminError);
}
await dbConnect();
const targetUser = await User.findById(params.id);
if (!targetUser) {
return NextResponse.json(
{
message: "User not found",
status: "error",
},
{ status: 404 },
);
}
await User.findByIdAndDelete(params.id);
return NextResponse.json({
message: "User deleted successfully",
status: "success",
});
} catch (error) {
console.error("Error deleting user:", error);
return NextResponse.json(
{
message: "Failed to delete user",
error: String(error),
status: "error",
},
{ status: 500 },
);
}
}