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
210 lines (184 loc) · 5.62 KB
/
Copy pathroute.ts
File metadata and controls
210 lines (184 loc) · 5.62 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
import { NextRequest, NextResponse } from "next/server";
import { authenticateUser, createAuthErrorResponse, requireEmailVerified, requireRegistrationOpen } from "@/lib/middleware/auth";
import dbConnect from "@/lib/db";
import User from "@/models/User";
import Team from "@/models/Team";
import TeamJoinRequest from "@/models/TeamJoinRequest";
// Configure route
export const dynamic = 'force-dynamic';
// Max team members
const MAX_TEAM_MEMBERS = 2;
// 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 });
}
/**
* PUT /api/team/join
* Join a team using team code
*/
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 deadlineError = requireRegistrationOpen();
if (deadlineError) {
return createAuthErrorResponse(deadlineError);
}
const body = await request.json();
const { teamCode } = body;
// Validation
if (!teamCode?.trim()) {
return NextResponse.json(
{ message: "Team code is required" },
{ status: 400 }
);
}
await dbConnect();
// Check if user is already in a team
const user = await User.findOne({ uid: authResult.user.uid });
if (!user) {
return NextResponse.json(
{ message: "User not found" },
{ status: 404 }
);
}
if (user.teamCode) {
return NextResponse.json(
{ message: "User already in a team" },
{ status: 400 }
);
}
// Find the team
const team = await Team.findOne({ teamCode: teamCode.trim().toUpperCase() });
if (!team) {
return NextResponse.json(
{ message: "Invalid team code" },
{ status: 404 }
);
}
// Check if team is full
if ((team.teamMembers || []).length >= MAX_TEAM_MEMBERS) {
return NextResponse.json(
{ message: "Team is full" },
{ status: 409 }
);
}
// Check if team has already submitted
if (team.teamStatus === 'submitted') {
return NextResponse.json(
{ message: "Team already submitted" },
{ status: 409 }
);
}
const targetCode = team.teamCode;
let updatedTeam;
try {
const seatFilter: Record<string, any> = {
teamCode: targetCode,
teamStatus: { $ne: "submitted" },
"teamMembers.uid": { $ne: authResult.user.uid },
};
seatFilter[`teamMembers.${MAX_TEAM_MEMBERS - 1}`] = { $exists: false };
updatedTeam = await Team.findOneAndUpdate(
seatFilter,
{
$push: {
teamMembers: {
uid: authResult.user.uid,
joinedAt: new Date(),
role: "Member",
},
},
$inc: { memberCount: 1 },
},
{ new: true }
);
} catch (err: any) {
if (err?.code === 11000) {
return NextResponse.json(
{ message: "User already in a team" },
{ status: 400 }
);
}
throw err;
}
if (!updatedTeam) {
const current = await Team.findOne({ teamCode: targetCode });
if (!current) {
return NextResponse.json({ message: "Invalid team code" }, { status: 404 });
}
if (current.teamMembers?.some((m: any) => m.uid === authResult.user.uid)) {
return NextResponse.json({ message: "User already in a team" }, { status: 400 });
}
if (current.teamStatus === "submitted") {
return NextResponse.json({ message: "Team already submitted" }, { status: 409 });
}
return NextResponse.json({ message: "Team is full" }, { status: 409 });
}
await User.findOneAndUpdate(
{ uid: authResult.user.uid },
{ teamCode: targetCode, isLooking: false }
);
// Cancel all pending join requests for this user
await TeamJoinRequest.updateMany(
{
userId: authResult.user.uid,
status: 'pending',
},
{
status: 'cancelled',
respondedAt: new Date(),
}
);
// Get team members with names (from the authoritative post-update document)
const memberUids = updatedTeam.teamMembers.map((m: any) => m.uid);
const members = await User.find({ uid: { $in: memberUids } }).select('uid name');
const formattedMembers = updatedTeam.teamMembers.map((member: any) => {
const userInfo = members.find((u: any) => u.uid === member.uid);
return {
id: member.uid,
name: userInfo?.name || 'Unknown',
role: member.role,
};
});
return NextResponse.json({
success: true,
message: "Successfully joined team",
data: {
teamCode: updatedTeam.teamCode,
teamName: updatedTeam.teamName,
teamMembers: formattedMembers,
memberCount: updatedTeam.memberCount,
},
});
} catch (error: any) {
console.error("Join team error:", error);
return NextResponse.json(
{ message: "Server error" },
{ status: 500 }
);
}
}