Files
moybeach-main/app/admin/users/actions.ts
T

69 lines
1.8 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
'use server';
import { prisma } from '@/lib/db';
import { getSession } from '@/lib/auth';
import { redirect } from 'next/navigation';
import { revalidatePath } from 'next/cache';
import bcrypt from 'bcryptjs';
async function requireAuth() {
const session = await getSession();
if (!session) redirect('/admin/login');
}
export async function createUser(formData: FormData) {
await requireAuth();
const username = formData.get('username') as string;
const password = formData.get('password') as string;
const confirmPassword = formData.get('confirmPassword') as string;
if (!username || !password) return;
if (password !== confirmPassword) return;
if (password.length < 6) return;
const exists = await prisma.user.findUnique({ where: { username } });
if (exists) return;
const hashed = await bcrypt.hash(password, 10);
await prisma.user.create({
data: { username, password: hashed },
});
revalidatePath('/admin/users');
}
export async function deleteUser(formData: FormData) {
await requireAuth();
const id = formData.get('id') as string;
if (!id) return;
// En az 1 kullanıcı kalsın
const count = await prisma.user.count();
if (count <= 1) return;
await prisma.user.delete({ where: { id } });
revalidatePath('/admin/users');
}
export async function changePassword(formData: FormData) {
await requireAuth();
const userId = formData.get('userId') as string;
const newPassword = formData.get('newPassword') as string;
const confirmPassword = formData.get('confirmPassword') as string;
if (!userId || !newPassword) return;
if (newPassword !== confirmPassword) return;
if (newPassword.length < 6) return;
const hashed = await bcrypt.hash(newPassword, 10);
await prisma.user.update({
where: { id: userId },
data: { password: hashed },
});
revalidatePath('/admin/users');
}