-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathroute.ts
More file actions
76 lines (66 loc) · 2.06 KB
/
route.ts
File metadata and controls
76 lines (66 loc) · 2.06 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
import { NextRequest, NextResponse } from "next/server";
import { cookies } from "next/headers";
import { db } from "@/lib/db";
import { users } from "@/schema";
import { eq } from "drizzle-orm";
import { logger } from "@/lib/logger";
export async function POST(request: NextRequest) {
try {
const { email, password } = await request.json();
await logger.info("login_attempt", { email });
if (!email || !password) {
await logger.warn("login_failed", {
email,
reason: "missing_credentials",
});
return NextResponse.json(
{ error: "Email and password are required" },
{ status: 400 }
);
}
const user = await db
.select()
.from(users)
.where(eq(users.email, email))
.limit(1);
if (user.length === 0) {
await logger.warn("login_failed", { email, reason: "user_not_found" });
return NextResponse.json(
{ error: "Invalid credentials" },
{ status: 401 }
);
}
// Compare plain text passwords (since they're stored as plain text)
const isValidPassword = password === user[0].password;
if (!isValidPassword) {
await logger.warn("login_failed", { email, reason: "invalid_password" });
return NextResponse.json(
{ error: "Invalid credentials" },
{ status: 401 }
);
}
const cookieStore = await cookies();
cookieStore.set("userId", user[0].id.toString(), {
httpOnly: true,
secure: process.env.NODE_ENV === "production",
sameSite: "strict",
maxAge: 60 * 60 * 24 * 7,
});
await logger.info(
"login_success",
{ email, userId: user[0].id.toString() },
user[0].id.toString()
);
return NextResponse.json({
message: "Login successful",
user: { id: user[0].id, name: user[0].name, email: user[0].email },
});
} catch (error: any) {
await logger.error("login_error", { error: error.message });
console.error("Login error:", error);
return NextResponse.json(
{ error: "Internal server error" },
{ status: 500 }
);
}
}