forked from UKSOURCE/ipv6
Adding login admin, fix ipv6 Vienamese version, add env example
This commit is contained in:
@@ -0,0 +1,48 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import dbConnect from "@/lib/mongodb";
|
||||
import User from "@/models/User";
|
||||
import crypto from "crypto";
|
||||
|
||||
function hashPassword(password: string) {
|
||||
return crypto.createHash("sha256").update(password).digest("hex");
|
||||
}
|
||||
|
||||
export async function POST(request: Request) {
|
||||
try {
|
||||
await dbConnect();
|
||||
const { email, password } = await request.json();
|
||||
|
||||
// Tìm user và chuẩn hóa email về chữ thường
|
||||
const user = await User.findOne({ email: email.toLowerCase().trim() });
|
||||
|
||||
if (!user) {
|
||||
console.log(`Login failed: User not found -> ${email}`);
|
||||
return NextResponse.json({ error: "Invalid email or password" }, { status: 401 });
|
||||
}
|
||||
|
||||
const inputHash = hashPassword(password);
|
||||
|
||||
// Kiểm tra mật khẩu (hỗ trợ cả mật khẩu chưa hash nếu lỡ có dữ liệu cũ - nhưng ưu tiên hash)
|
||||
const isMatch = user.password === inputHash || user.password === password;
|
||||
|
||||
if (!isMatch) {
|
||||
console.log(`Login failed: Password mismatch for -> ${email}`);
|
||||
return NextResponse.json({ error: "Invalid email or password" }, { status: 401 });
|
||||
}
|
||||
|
||||
const response = NextResponse.json({ success: true });
|
||||
|
||||
response.cookies.set("admin_session", "true", {
|
||||
httpOnly: true,
|
||||
secure: process.env.NODE_ENV === "production",
|
||||
sameSite: "lax",
|
||||
path: "/",
|
||||
maxAge: 60 * 60 * 24,
|
||||
});
|
||||
|
||||
return response;
|
||||
} catch (error) {
|
||||
console.error("Login error:", error);
|
||||
return NextResponse.json({ error: "Internal server error" }, { status: 500 });
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user