feat: setup database-driven admin user management

This commit is contained in:
2026-06-10 04:25:54 +03:00
parent f542efb324
commit b712760825
23 changed files with 804 additions and 40 deletions
+52 -16
View File
@@ -2,29 +2,65 @@
import { cookies } from "next/headers";
import { redirect } from "next/navigation";
import prisma from "@/lib/prisma";
import bcrypt from "bcryptjs";
export type ActionState = { error: string } | null;
export async function login(prevState: ActionState, formData: FormData): Promise<ActionState> {
const username = formData.get("username");
const password = formData.get("password");
const username = formData.get("username") as string;
const password = formData.get("password") as string;
if (
username === process.env.ADMIN_USERNAME &&
password === process.env.ADMIN_PASSWORD
) {
const cookieStore = await cookies();
cookieStore.set("admin_session", "true", {
httpOnly: true,
secure: process.env.NODE_ENV === "production",
maxAge: 60 * 60 * 24 * 7, // 1 week
path: "/",
});
} else {
return { error: "Geçersiz kullanıcı adı veya şifre" };
if (!username || !password) {
return { error: "Kullanıcı adı ve şifre gereklidir" };
}
redirect("/admin");
// Fallback to initial .env credentials if no users exist
const userCount = await prisma.user.count();
if (userCount === 0) {
if (
username === process.env.ADMIN_USERNAME &&
password === process.env.ADMIN_PASSWORD
) {
// Create the first admin user
const hashedPassword = await bcrypt.hash(password, 10);
await prisma.user.create({
data: {
username,
password: hashedPassword,
},
});
await setSessionCookie();
redirect("/admin");
} else {
return { error: "Geçersiz kullanıcı adı veya şifre" };
}
} else {
// Normal DB login
const user = await prisma.user.findUnique({
where: { username },
});
if (user && await bcrypt.compare(password, user.password)) {
await setSessionCookie();
redirect("/admin");
} else {
return { error: "Geçersiz kullanıcı adı veya şifre" };
}
}
// This redirect is inside if blocks but typescript requires a return here.
return { error: "Bilinmeyen bir hata oluştu" };
}
async function setSessionCookie() {
const cookieStore = await cookies();
cookieStore.set("admin_session", "true", {
httpOnly: true,
secure: process.env.NODE_ENV === "production",
maxAge: 60 * 60 * 24 * 7, // 1 week
path: "/",
});
}
export async function logout() {