-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathroute.ts
More file actions
177 lines (160 loc) · 5.56 KB
/
Copy pathroute.ts
File metadata and controls
177 lines (160 loc) · 5.56 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
import { auth } from "@/Firebase";
import { signInWithEmailAndPassword, createUserWithEmailAndPassword } from "firebase/auth";
import { FirebaseError } from "firebase/app";
import { NextResponse } from "next/server";
import dbConnect from "@/lib/db";
import User from "@/models/User";
import { getAuth } from "@/lib/firebase-admin";
const ADMIN_EMAIL_DOMAIN = process.env.ADMIN_EMAIL_DOMAIN;
const SECRET_CODE = process.env.SECRET_CODE;
// Helper function to create error response
const createErrorResponse = (message: string, status: number, errorCode?: string) => {
return NextResponse.json(
{ message, status: "error", ...(errorCode && { error: errorCode }) },
{ status }
);
};
// Handle authentication with Firebase
const authenticateUser = async (email: string, password: string, isAdminAttempt: boolean) => {
try {
return await signInWithEmailAndPassword(auth, email, password);
} catch (authError: unknown) {
if (authError instanceof FirebaseError && isAdminAttempt &&
(authError.code === 'auth/invalid-credential' ||
authError.code === 'auth/user-not-found')) {
// Create new admin account if login fails with valid admin domain
return await createUserWithEmailAndPassword(auth, email, password);
}
// For non-admin users or other errors, propagate the error
throw authError;
}
};
export async function POST(request: Request) {
try {
const { email, password } = await request.json();
if (!email || !password) {
return createErrorResponse("Email and password are required", 400);
}
const isAdminAttempt = email.endsWith(ADMIN_EMAIL_DOMAIN) && password === SECRET_CODE;
// Authentication phase
const userCredential = await authenticateUser(email, password, isAdminAttempt);
const firebaseUser = userCredential.user;
const idToken = await firebaseUser.getIdToken();
await dbConnect();
let user = await User.findOne({ uid: firebaseUser.uid });
if (!user) {
user = await User.findOne({ email: email });
}
// Process based on user type
if (isAdminAttempt) {
// Admin login flow
if (user) {
if (user.role !== 'admin') {
await User.findByIdAndUpdate(user._id, { role: 'admin' });
user.role = 'admin';
}
try {
await getAuth().updateUser(firebaseUser.uid, {
emailVerified: true
});
} catch (verifyError) {
console.error('Failed to verify admin email:', verifyError);
}
return NextResponse.json({
message: "Login successful",
status: "success",
user: {
uid: user.uid,
email: user.email,
name: user.name,
isAdmin: true,
profile_picture: user.profile_picture || null,
status: "active"
},
token: idToken
});
} else {
const adminName = email.split('@')[0].split('.')
.map((s: string) => s.charAt(0).toUpperCase() + s.slice(1))
.join(' ');
const newAdminUser = await new User({
uid: firebaseUser.uid,
name: adminName,
email: email,
role: 'admin',
isLooking: false
}).save();
try {
await getAuth().updateUser(firebaseUser.uid, {
emailVerified: true
});
await getAuth().setCustomUserClaims(firebaseUser.uid, { role: 'admin' });
} catch (adminError) {
console.error('Failed to verify admin email or set claims:', adminError);
}
return NextResponse.json({
message: "Login successful. Admin privileges granted.",
status: "success",
user: {
uid: newAdminUser.uid,
email: newAdminUser.email,
name: newAdminUser.name,
isAdmin: true,
profile_picture: newAdminUser.profile_picture || null,
status: "active"
},
token: idToken
});
}
} else {
if (!user) {
return createErrorResponse("User record not found", 404);
}
return NextResponse.json({
message: "Login successful",
status: "success",
user: {
uid: user.uid,
email: user.email,
name: user.name,
isAdmin: user.role === 'admin',
profile_picture: user.profile_picture || null,
status: "active"
},
token: idToken
});
}
} catch (error: unknown) {
console.error("Login error:", error);
const errorCode = error instanceof FirebaseError ? error.code : undefined;
let errorMessage = "Login failed";
let statusCode = 500;
switch (errorCode) {
case 'auth/invalid-email':
errorMessage = "Invalid email format";
statusCode = 400;
break;
case 'auth/invalid-credential':
errorMessage = "Invalid credentials";
statusCode = 400;
break;
case 'auth/user-disabled':
errorMessage = "This account has been disabled";
statusCode = 403;
break;
case 'auth/user-not-found':
errorMessage = "No account found with this email";
statusCode = 404;
break;
case 'auth/wrong-password':
errorMessage = "Incorrect password";
statusCode = 401;
break;
case 'auth/too-many-requests':
errorMessage = "Too many unsuccessful login attempts. Please try again later";
statusCode = 429;
break;
}
return createErrorResponse(errorMessage, statusCode, errorCode);
}
}