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
383 lines (349 loc) · 10.6 KB
/
Copy pathroute.ts
File metadata and controls
383 lines (349 loc) · 10.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
import { NextRequest, NextResponse } from "next/server";
import {
authenticateUser,
createAuthErrorResponse,
isAuthError,
requireEmailVerified,
} from "@/lib/middleware/auth";
import { cloudinaryV2 } from "@/c";
import dbConnect from "@/lib/db";
import User from "@/models/User";
import Team from "@/models/Team";
import { verifyRecaptcha } from "@/lib/recaptcha";
// 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,
});
// Helper to create success response
function createSuccessResponse(message: string, data: any, status = 200) {
return NextResponse.json(
{
success: true,
message,
data,
timestamp: new Date().toISOString(),
},
{ status },
);
}
// Helper to create error response
function createErrorResponse(
message: string,
code: string,
status: number,
details?: string,
) {
return NextResponse.json(
{
success: false,
message,
error: { code, message, details },
timestamp: new Date().toISOString(),
},
{ status },
);
}
// 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);
},
);
});
}
// Extract public ID from Cloudinary URL for deletion
function extractPublicIdFromUrl(url: string): string | null {
try {
const match = url.match(/\/upload\/(?:v\d+\/)?(.+?)(?:\.\w+)?$/);
return match ? match[1] : null;
} catch {
return null;
}
}
// Delete file from Cloudinary
async function deleteFromCloudinary(
url: string,
resourceType: string = "image",
): Promise<boolean> {
const publicId = extractPublicIdFromUrl(url);
if (!publicId) return false;
try {
await cloudinaryV2.uploader.destroy(publicId, {
resource_type: resourceType,
});
return true;
} catch {
return false;
}
}
// Validate an optional profile link. Empty/undefined is allowed (the field can
// be cleared); a provided value must be a well-formed absolute http(s) URL with
// a real hostname — non-web schemes (javascript:, data:, mailto:, …) are
// rejected so we never store a value that breaks or could be used for injection.
function isValidLinkUrl(value: unknown): boolean {
if (value === undefined || value === null) return true;
if (typeof value !== "string") return false;
const trimmed = value.trim();
if (!trimmed) return true;
let parsed: URL;
try {
parsed = new URL(trimmed);
} catch {
return false;
}
return (
(parsed.protocol === "https:" || parsed.protocol === "http:") &&
parsed.hostname.includes(".") &&
/^[a-zA-Z0-9.-]+$/.test(parsed.hostname)
);
}
// Same as isValidLinkUrl, but the host must be (a subdomain of) one of
// `domains`. Used for fields that must point at a specific site (GitHub /
// LinkedIn). A leading `www.` is ignored.
function isValidLinkDomain(value: unknown, domains: string[]): boolean {
if (value === undefined || value === null) return true;
if (typeof value !== "string" || !value.trim()) return true;
if (!isValidLinkUrl(value)) return false;
const host = new URL(value.trim())
.hostname.toLowerCase()
.replace(/^www\./, "");
return domains.some((d) => host === d || host.endsWith(`.${d}`));
}
/**
* GET /api/user/profile
* Get authenticated user's profile
*/
export async function GET(request: NextRequest) {
try {
const authResult = await authenticateUser(request);
if (!authResult.success) {
return NextResponse.json(
{ message: authResult.error.message },
{ status: authResult.status },
);
}
await dbConnect();
const user = await User.findOne({ uid: authResult.user.uid }).select(
"-__v",
);
if (!user) {
return NextResponse.json({ message: "User not found" }, { status: 404 });
}
const responseData: any = {
uid: user.uid,
name: user.name,
email: user.email,
phone: user.phone || null,
discord_username: user.discord_username || null,
resume_link: user.resume_link || null,
profile_picture: user.profile_picture || 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,
role: user.role,
isLooking: user.isLooking,
teamCode: user.teamCode || null,
hasSolvedChallenge: user.hasSolvedChallenge || false,
isProfileLocked: false,
};
if (user.teamCode) {
const team = await Team.findOne({ teamCode: user.teamCode });
if (team && team.isEvaluated) {
responseData.isProfileLocked = true;
}
}
return NextResponse.json({
success: true,
data: responseData,
});
} catch (error: any) {
console.error("Get profile error:", error);
return NextResponse.json({ message: "Server error" }, { status: 500 });
}
}
/**
* PUT /api/user/profile
* Update authenticated user's profile
*/
export async function PUT(request: NextRequest) {
try {
const authResult = await authenticateUser(request);
if (!authResult.success) {
return NextResponse.json(
{ message: authResult.error.message },
{ status: authResult.status },
);
}
const emailError = requireEmailVerified(authResult);
if (emailError) {
return createAuthErrorResponse(emailError);
}
const body = await request.json();
// reCAPTCHA v3 background score check — reject likely-bot/scripted uploads.
const captcha = await verifyRecaptcha(
body.recaptcha_token,
"update_profile",
);
if (!captcha.ok) {
console.warn(
"[user/profile] reCAPTCHA rejected:",
captcha.reason,
captcha.score,
);
return NextResponse.json(
{
message: "reCAPTCHA verification failed",
error: {
code: "recaptcha_failed",
message: "reCAPTCHA verification failed",
},
},
{ status: 400 },
);
}
// Fields that can be updated
const {
name,
bio,
phone,
discord_username,
organisation,
age,
resume, // base64 encoded PDF
profile_picture, // base64 encoded image
github_link,
linkedin_link,
portfolio_link,
ctf_profile,
isLooking,
} = body;
// Validate profile links. Empty clears the field; a provided value must be
// a well-formed http(s) URL (and the correct site for GitHub / LinkedIn).
if (!isValidLinkDomain(github_link, ["github.com"])) {
return createErrorResponse(
"Please enter a valid GitHub URL (e.g. https://github.com/username)",
"invalid_url",
400,
);
}
if (!isValidLinkDomain(linkedin_link, ["linkedin.com"])) {
return createErrorResponse(
"Please enter a valid LinkedIn URL (e.g. https://linkedin.com/in/username)",
"invalid_url",
400,
);
}
if (!isValidLinkUrl(portfolio_link)) {
return createErrorResponse(
"Please enter a valid portfolio URL (https://…)",
"invalid_url",
400,
);
}
if (!isValidLinkUrl(ctf_profile)) {
return createErrorResponse(
"Please enter a valid CTF profile URL (https://…)",
"invalid_url",
400,
);
}
await dbConnect();
const user = await User.findOne({ uid: authResult.user.uid });
if (!user) {
return NextResponse.json({ message: "User not found" }, { status: 404 });
}
// Check if profile is locked
if (user.teamCode) {
const team = await Team.findOne({ teamCode: user.teamCode });
if (team && team.isEvaluated) {
return NextResponse.json(
{ message: "Profile cannot be edited after team evaluation" },
{ status: 403 },
);
}
}
// Build update object with only provided fields
const updateData: Record<string, any> = {};
if (bio !== undefined) updateData.bio = bio.trim();
if (discord_username !== undefined)
updateData.discord_username = discord_username.trim();
if (organisation !== undefined)
updateData.organisation = organisation.trim();
if (github_link !== undefined)
updateData.github_link = github_link?.trim() || null;
if (linkedin_link !== undefined)
updateData.linkedin_link = linkedin_link?.trim() || null;
if (portfolio_link !== undefined)
updateData.portfolio_link = portfolio_link?.trim() || null;
if (ctf_profile !== undefined)
updateData.ctf_profile = ctf_profile?.trim() || null;
if (isLooking !== undefined) updateData.isLooking = Boolean(isLooking);
// Handle file uploads
if (resume) {
try {
// Delete old resume if exists
if (user.resume_link) {
await deleteFromCloudinary(user.resume_link, "raw");
}
updateData.resume_link = await uploadBase64ToCloudinary(
resume,
"zenith/resumes",
"raw",
);
} catch (uploadError) {
console.error("Resume upload error:", uploadError);
}
}
if (profile_picture) {
try {
// Delete old profile picture if exists
if (user.profile_picture) {
await deleteFromCloudinary(user.profile_picture, "image");
}
updateData.profile_picture = await uploadBase64ToCloudinary(
profile_picture,
"zenith/profiles",
"image",
);
} catch (uploadError) {
console.error("Profile picture upload error:", uploadError);
}
}
// Update user
const updatedUser = await User.findOneAndUpdate(
{ uid: authResult.user.uid },
{ $set: updateData },
{ new: true },
);
if (!updatedUser) {
return NextResponse.json({ message: "User not found" }, { status: 404 });
}
return NextResponse.json({
message: "User updated successfully",
id: updatedUser._id.toString(),
uid: updatedUser.uid,
status: "success",
});
} catch (error: any) {
console.error("Update profile error:", error);
return NextResponse.json({ message: "Server error" }, { status: 500 });
}
}