Files
kite-qr/app/admin/(dashboard)/users/actions.ts
T
2026-06-11 13:25:26 +03:00

72 lines
2.4 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/prisma'
import bcrypt from 'bcryptjs'
import { revalidatePath } from 'next/cache'
export async function createUser(_prevState: unknown, formData: FormData) {
const username = (formData.get('username') as string)?.trim()
const password = formData.get('password') as string
const role = (formData.get('role') as string) || 'admin'
if (!username || !password) {
return { error: 'Kullanıcı adı ve şifre zorunludur.' }
}
if (password.length < 6) {
return { error: 'Şifre en az 6 karakter olmalıdır.' }
}
try {
const existing = await prisma.users.findUnique({ where: { username } })
if (existing) {
return { error: 'Bu kullanıcı adı zaten kullanılıyor.' }
}
const password_hash = await bcrypt.hash(password, 12)
await prisma.users.create({ data: { username, password_hash, role } })
revalidatePath('/admin/users')
return { success: true }
} catch (error) {
console.error('Create user error:', error)
return { error: 'Kullanıcı oluşturulurken hata oluştu.' }
}
}
export async function changePassword(userId: number, _prevState: unknown, formData: FormData) {
const newPassword = formData.get('new_password') as string
const confirmPassword = formData.get('confirm_password') as string
if (!newPassword || newPassword.length < 6) {
return { error: 'Şifre en az 6 karakter olmalıdır.' }
}
if (newPassword !== confirmPassword) {
return { error: 'Şifreler eşleşmiyor.' }
}
try {
const password_hash = await bcrypt.hash(newPassword, 12)
await prisma.users.update({ where: { id: userId }, data: { password_hash } })
revalidatePath('/admin/users')
return { success: true, message: 'Şifre güncellendi.' }
} catch (error) {
console.error('Change password error:', error)
return { error: 'Şifre güncellenirken hata oluştu.' }
}
}
export async function deleteUser(userId: number) {
try {
// Count total users — don't allow deleting the last admin
const count = await prisma.users.count()
if (count <= 1) {
return { error: 'Son yönetici kullanıcı silinemez.' }
}
await prisma.users.delete({ where: { id: userId } })
revalidatePath('/admin/users')
return { success: true }
} catch (error) {
console.error('Delete user error:', error)
return { error: 'Kullanıcı silinirken hata oluştu.' }
}
}