enhancment complete with phase 10
This commit is contained in:
1 parent
2c4927478a
commit
6adb541967
44 files changed
+7820
-845
No files matched your search
@@ -2,48 +2,50 @@ import { NextRequest, NextResponse } from "next/server";
|
||||
import bcrypt from "bcryptjs";
|
||||
import { getDatabase } from "../../../../lib/database/index";
|
||||
import log from "@/lib/logger";
|
||||
import { userLoginSchema } from "@/lib/validation/schemas";
|
||||
import {
|
||||
validateRequestBody,
|
||||
validationErrorResponse,
|
||||
} from "@/lib/validation/helpers";
|
||||
import {
|
||||
successResponse,
|
||||
unauthorizedResponse,
|
||||
internalErrorResponse,
|
||||
} from "@/lib/api/responses";
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const db = await getDatabase();
|
||||
const { email, password } = await request.json();
|
||||
// Validate request body
|
||||
const validation = await validateRequestBody(request, userLoginSchema);
|
||||
|
||||
if (!email || !password) {
|
||||
return NextResponse.json(
|
||||
{ error: "Email and password are required" },
|
||||
{ status: 400 },
|
||||
);
|
||||
if (!validation.success) {
|
||||
log.warn("Login validation failed", { errors: validation.errors });
|
||||
return validationErrorResponse(validation.errors);
|
||||
}
|
||||
|
||||
const { email, password } = validation.data;
|
||||
|
||||
const db = await getDatabase();
|
||||
const user = await db.getUserByEmail(email);
|
||||
|
||||
if (!user) {
|
||||
return NextResponse.json(
|
||||
{ error: "Invalid credentials" },
|
||||
{ status: 401 },
|
||||
);
|
||||
return unauthorizedResponse("Invalid credentials");
|
||||
}
|
||||
|
||||
const isValidPassword = await bcrypt.compare(password, user.password);
|
||||
|
||||
if (!isValidPassword) {
|
||||
return NextResponse.json(
|
||||
{ error: "Invalid credentials" },
|
||||
{ status: 401 },
|
||||
);
|
||||
return unauthorizedResponse("Invalid credentials");
|
||||
}
|
||||
|
||||
const { password: _, ...userWithoutPassword } = user;
|
||||
|
||||
return NextResponse.json({
|
||||
return successResponse({
|
||||
message: "Login successful",
|
||||
user: userWithoutPassword,
|
||||
});
|
||||
} catch (error) {
|
||||
log.error("Login failed", error);
|
||||
return NextResponse.json(
|
||||
{ error: "Internal server error" },
|
||||
{ status: 500 },
|
||||
);
|
||||
return internalErrorResponse();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user