-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathauth.ts
More file actions
276 lines (246 loc) · 6.46 KB
/
Copy pathauth.ts
File metadata and controls
276 lines (246 loc) · 6.46 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
import { NextRequest, NextResponse } from 'next/server';
import { getAuth } from '@/lib/firebase-admin';
import dbConnect from '@/lib/db';
import User, { IUser } from '@/models/User';
import Team from '@/models/Team';
import { isRegistrationClosed } from '@/lib/constants';
// Types for authenticated requests
export interface AuthenticatedUser {
uid: string;
email: string;
name: string;
role: 'user' | 'admin' | 'evaluator' | 'frai';
teamCode?: string;
isLooking: boolean;
_id: string;
}
export interface AuthResult {
success: true;
user: AuthenticatedUser;
firebaseToken: {
uid: string;
email?: string;
email_verified?: boolean;
};
}
export interface AuthError {
success: false;
error: {
code: string;
message: string;
};
status: number;
}
type AuthResponse = AuthResult | AuthError;
/**
* Verify Firebase token and get user from database
* Returns user data if authenticated, error object if not
*/
export async function authenticateUser(request: NextRequest): Promise<AuthResponse> {
try {
const authHeader = request.headers.get('authorization');
if (!authHeader || !authHeader.startsWith('Bearer ')) {
return {
success: false,
error: { code: 'AUTH_REQUIRED', message: 'Authentication required' },
status: 401,
};
}
const token = authHeader.split('Bearer ')[1];
if (!token) {
return {
success: false,
error: { code: 'AUTH_REQUIRED', message: 'Invalid authorization header' },
status: 401,
};
}
// Verify token with Firebase Admin
let decodedToken;
try {
decodedToken = await getAuth().verifyIdToken(token);
} catch (firebaseError: any) {
// Handle specific Firebase errors
if (firebaseError.code === 'auth/id-token-expired') {
return {
success: false,
error: { code: 'TOKEN_EXPIRED', message: 'Authentication token has expired' },
status: 401,
};
}
if (firebaseError.code === 'auth/argument-error') {
return {
success: false,
error: { code: 'TOKEN_INVALID', message: 'Invalid authentication token' },
status: 401,
};
}
throw firebaseError;
}
// Connect to database and fetch user
await dbConnect();
const user = await User.findOne({ uid: decodedToken.uid });
if (!user) {
return {
success: false,
error: { code: 'USER_NOT_FOUND', message: 'User not found in database' },
status: 404,
};
}
return {
success: true,
user: {
uid: user.uid,
email: user.email,
name: user.name,
role: user.role,
teamCode: user.teamCode,
isLooking: user.isLooking,
_id: user._id.toString(),
},
firebaseToken: {
uid: decodedToken.uid,
email: decodedToken.email,
email_verified: decodedToken.email_verified,
},
};
} catch (error: any) {
console.error('Authentication error:', error);
return {
success: false,
error: { code: 'AUTH_ERROR', message: 'Authentication failed' },
status: 500,
};
}
}
/**
* Check if authenticated user is an admin
*/
export function requireAdmin(authResult: AuthResult): AuthError | null {
if (authResult.user.role !== 'admin') {
return {
success: false,
error: { code: 'FORBIDDEN', message: 'Admin access required' },
status: 403,
};
}
return null;
}
/**
* Check if authenticated user is an evaluator
*/
export function requireEvaluator(authResult: AuthResult): AuthError | null {
if (authResult.user.role !== 'evaluator') {
return {
success: false,
error: { code: 'FORBIDDEN', message: 'Evaluator access required' },
status: 403,
};
}
return null;
}
/**
* Reject the request if the registration / team-formation deadline has passed.
*/
export function requireRegistrationOpen(): AuthError | null {
if (isRegistrationClosed()) {
return {
success: false,
error: {
code: 'REGISTRATION_CLOSED',
message:
'The registration deadline has passed. Team changes are no longer allowed.',
},
status: 403,
};
}
return null;
}
/**
* Check if authenticated user has verified email
*/
export function requireEmailVerified(authResult: AuthResult): AuthError | null {
if (authResult.user.role === 'admin') {
return null;
}
if (authResult.firebaseToken.email_verified !== true) {
return {
success: false,
error: { code: 'EMAIL_NOT_VERIFIED', message: 'Email verification required' },
status: 403,
};
}
return null;
}
/**
* Check if authenticated user is team lead for a specific team
*/
export async function requireTeamLead(
authResult: AuthResult,
teamCode: string
): Promise<{ team: any } | AuthError> {
await dbConnect();
const team = await Team.findOne({ teamCode });
if (!team) {
return {
success: false,
error: { code: 'NOT_FOUND', message: 'Team not found' },
status: 404,
};
}
if (team.teamLead !== authResult.user.uid) {
return {
success: false,
error: { code: 'NOT_TEAM_LEAD', message: 'Only team lead can perform this action' },
status: 403,
};
}
return { team };
}
/**
* Check if authenticated user is a member of a specific team
*/
export async function requireTeamMember(
authResult: AuthResult,
teamCode: string
): Promise<{ team: any } | AuthError> {
await dbConnect();
const team = await Team.findOne({ teamCode });
if (!team) {
return {
success: false,
error: { code: 'NOT_FOUND', message: 'Team not found' },
status: 404,
};
}
const isMember = team.teamMembers.some(
(member: any) => member.uid === authResult.user.uid || member === authResult.user.uid
);
if (!isMember) {
return {
success: false,
error: { code: 'FORBIDDEN', message: 'Must be a team member' },
status: 403,
};
}
return { team };
}
/**
* Helper to create error response
*/
export function createAuthErrorResponse(error: AuthError): NextResponse {
return NextResponse.json(
{
success: false,
message: error.error.message,
error: error.error,
timestamp: new Date().toISOString(),
},
{ status: error.status }
);
}
/**
* Helper to check if result is an error
*/
export function isAuthError(result: AuthResponse | { team: any }): result is AuthError {
return 'success' in result && result.success === false;
}