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
179 lines (152 loc) · 4.91 KB
/
Copy pathroute.ts
File metadata and controls
179 lines (152 loc) · 4.91 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
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';
// 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 });
}
// Generate unique 6-8 character alphanumeric team code
async function generateTeamCode(): Promise<string> {
const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
const length = Math.floor(Math.random() * 3) + 6; // 6-8 characters
let attempts = 0;
const maxAttempts = 10;
while (attempts < maxAttempts) {
let code = '';
for (let i = 0; i < length; i++) {
code += characters.charAt(Math.floor(Math.random() * characters.length));
}
// Check uniqueness
const existingTeam = await Team.findOne({ teamCode: code });
if (!existingTeam) {
return code;
}
attempts++;
}
throw new Error('Failed to generate unique team code');
}
// Check team name uniqueness (case-insensitive)
async function isTeamNameUnique(teamName: string): Promise<boolean> {
const existingTeam = await Team.findOne({
teamName: { $regex: new RegExp(`^${teamName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}$`, 'i') }
});
return !existingTeam;
}
/**
* POST /api/team/create
* Create a new team
*/
export async function POST(request: NextRequest) {
try {
const authResult = await authenticateUser(request);
if (!authResult.success) {
return createErrorResponse(authResult.error.message, 'auth_error', 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 { teamName, isLooking = false } = body;
// Validation
if (!teamName?.trim()) {
return createErrorResponse("Team name is required", 'validation_error', 400);
}
if (teamName.length < 2 || teamName.length > 50) {
return createErrorResponse("Team name must be 2-50 characters", 'validation_error', 400);
}
await dbConnect();
// Check if user is already in a team
const user = await User.findOne({ uid: authResult.user.uid });
if (!user) {
return createErrorResponse("User not found", 'user_not_found', 404);
}
if (user.teamCode) {
return createErrorResponse("User already in a team", 'already_in_team', 400);
}
// Check team name uniqueness
const isUnique = await isTeamNameUnique(teamName);
if (!isUnique) {
return createErrorResponse("Team name already exists", 'team_name_exists', 409);
}
// Generate unique team code
const teamCode = await generateTeamCode();
// Create team
const newTeam = new Team({
teamCode,
teamName: teamName.trim(),
teamLead: authResult.user.uid,
isLooking: Boolean(isLooking),
teamMembers: [{
uid: authResult.user.uid,
joinedAt: new Date(),
role: 'Team Lead',
}],
memberCount: 1,
teamStatus: 'pending',
});
await newTeam.save();
// Update user's teamCode
await User.findOneAndUpdate(
{ uid: authResult.user.uid },
{ teamCode, isLooking: false }
);
// Cancel all pending join requests and invitations for this user
await TeamJoinRequest.updateMany(
{
userId: authResult.user.uid,
status: 'pending',
},
{
status: 'cancelled',
respondedAt: new Date(),
}
);
return NextResponse.json({
success: true,
message: "Team created successfully",
data: {
teamCode,
teamName: newTeam.teamName,
teamLead: authResult.user.uid,
teamMembers: [{
id: authResult.user.uid,
name: user.name,
role: 'Team Lead',
}],
isLooking: newTeam.isLooking,
},
}, { status: 201 });
} catch (error: any) {
console.error("Create team error:", error);
return createErrorResponse(
error instanceof Error ? error.message : "Server error",
'server_error',
500,
process.env.NODE_ENV === 'development' ? String(error) : undefined
);
}
}