Files
parakasa/app/(dashboard)/dashboard/users/actions.ts
2026-01-10 20:38:06 +03:00

165 lines
5.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 { createClient } from "@/lib/supabase-server"
import { createClient as createSupabaseClient } from "@supabase/supabase-js"
import { revalidatePath } from "next/cache"
import { redirect } from "next/navigation"
// WARNING: specialized client for admin actions only
// This requires SUPABASE_SERVICE_ROLE_KEY to be set in .env.local
const supabaseAdmin = createSupabaseClient(
process.env.NEXT_PUBLIC_SUPABASE_URL!,
process.env.SUPABASE_SERVICE_ROLE_KEY!,
{
auth: {
autoRefreshToken: false,
persistSession: false
}
}
)
export async function createUser(firstName: string, lastName: string, email: string, password: string, role: 'admin' | 'user', phone?: string) {
const supabase = createClient()
// 1. Check if current user is admin
const { data: { user: currentUser } } = await supabase.auth.getUser()
if (!currentUser) return { error: "Oturum açmanız gerekiyor." }
const { data: profile } = await supabase
.from('profiles')
.select('role')
.eq('id', currentUser.id)
.single()
if (!profile || profile.role !== 'admin') {
return { error: "Yetkisiz işlem. Sadece yöneticiler kullanıcı oluşturabilir." }
}
// 2. Create user using Admin client
const { data: newUser, error: createError } = await supabaseAdmin.auth.admin.createUser({
email,
password,
email_confirm: true, // Auto confirm
user_metadata: {
full_name: `${firstName} ${lastName}`.trim()
}
})
if (createError) {
return { error: createError.message }
}
if (!newUser.user) {
return { error: "Kullanıcı oluşturulamadı." }
}
// 3. Create profile entry (if not handled by trigger, but we'll do it manually to be safe/explicit about role)
const { error: profileError } = await supabaseAdmin
.from('profiles')
.insert({
id: newUser.user.id,
full_name: `${firstName} ${lastName}`.trim(),
role: role,
phone: phone
})
if (profileError) {
// Optional: delete auth user if profile creation fails?
// For now just return error
return { error: "Kullanıcı oluşturuldu ancak profil kaydedilemedi: " + profileError.message }
}
revalidatePath("/dashboard/users")
return { success: true }
}
export async function deleteUser(userId: string) {
const supabase = createClient()
// Check admin
const { data: { user: currentUser } } = await supabase.auth.getUser()
if (!currentUser) return { error: "Oturum açmanız gerekiyor." }
const { data: profile } = await supabase.from('profiles').select('role').eq('id', currentUser.id).single()
if (profile?.role !== 'admin') return { error: "Yetkisiz işlem." }
// Delete user
const { error } = await supabaseAdmin.auth.admin.deleteUser(userId)
if (error) return { error: error.message }
revalidatePath("/dashboard/users")
return { success: true }
}
export async function updateUser(userId: string, data: { firstName: string, lastName: string, email: string, password?: string, role: 'admin' | 'user', phone?: string }) {
const supabase = createClient()
// Check admin
const { data: { user: currentUser } } = await supabase.auth.getUser()
if (!currentUser) return { error: "Oturum açmanız gerekiyor." }
// Check if current user is admin
const { data: profile } = await supabase.from('profiles').select('role').eq('id', currentUser.id).single()
if (profile?.role !== 'admin') return { error: "Yetkisiz işlem." }
// 1. Update Profile (Role and Name)
const { error: profileError } = await supabaseAdmin
.from('profiles')
.update({
full_name: `${data.firstName} ${data.lastName}`.trim(),
role: data.role,
phone: data.phone
})
.eq('id', userId)
if (profileError) return { error: "Profil güncellenemedi: " + profileError.message }
// 2. Update Auth (Email and Password)
const authUpdates: any = {
email: data.email,
user_metadata: {
full_name: `${data.firstName} ${data.lastName}`.trim()
}
}
if (data.password && data.password.length >= 6) {
authUpdates.password = data.password
}
const { error: authError } = await supabaseAdmin.auth.admin.updateUserById(userId, authUpdates)
if (authError) return { error: "Kullanıcı giriş bilgileri güncellenemedi: " + authError.message }
revalidatePath("/dashboard/users")
return { success: true }
}
export async function updateProfile(data: { firstName: string, lastName: string, phone?: string }) {
const supabase = createClient()
const { data: { user } } = await supabase.auth.getUser()
if (!user) return { error: "Oturum açmanız gerekiyor." }
const { error } = await supabase
.from('profiles')
.update({
full_name: `${data.firstName} ${data.lastName}`.trim(),
phone: data.phone
})
.eq('id', user.id)
if (error) return { error: "Profil güncellenemedi: " + error.message }
// Update Auth Metadata as well
if (data.firstName || data.lastName) {
await supabase.auth.updateUser({
data: {
full_name: `${data.firstName} ${data.lastName}`.trim()
}
})
}
revalidatePath("/dashboard/profile")
return { success: true }
}