Site Yönetimi,Kullanıcı Girişi,Karanlık mod özellikleri db bağlantıları.

This commit is contained in:
2026-01-08 23:56:28 +03:00
parent 6e02336827
commit ddf28e1892
40 changed files with 2545 additions and 96 deletions

View File

@@ -0,0 +1,22 @@
import { createClient } from "@/lib/supabase-server"
import { CategoryForm } from "@/components/dashboard/category-form"
import { notFound } from "next/navigation"
export default async function EditCategoryPage({ params }: { params: { id: string } }) {
const supabase = createClient()
const { data: category } = await supabase
.from('categories')
.select('*')
.eq('id', params.id)
.single()
if (!category) {
notFound()
}
return (
<div className="flex-1 space-y-4 p-8 pt-6">
<CategoryForm initialData={category} />
</div>
)
}

View File

@@ -0,0 +1,107 @@
"use server"
import { createClient } from "@/lib/supabase-server"
import { createClient as createSupabaseClient } from "@supabase/supabase-js"
import { revalidatePath } from "next/cache"
// Admin client for privileged operations
const supabaseAdmin = createSupabaseClient(
process.env.NEXT_PUBLIC_SUPABASE_URL!,
process.env.SUPABASE_SERVICE_ROLE_KEY!,
{
auth: {
autoRefreshToken: false,
persistSession: false
}
}
)
export async function createCategory(data: { name: string, description?: string, image_url?: string }) {
const supabase = createClient()
// Check admin
const { data: { user } } = await supabase.auth.getUser()
if (!user) return { error: "Oturum açmanız gerekiyor." }
// Check if current user is admin
const { data: profile } = await supabase.from('profiles').select('role').eq('id', user.id).single()
if (profile?.role !== 'admin') return { error: "Yetkisiz işlem." }
// Generate slug from name
const slug = data.name.toLowerCase()
.replace(/ğ/g, 'g')
.replace(/ü/g, 'u')
.replace(/ş/g, 's')
.replace(/ı/g, 'i')
.replace(/ö/g, 'o')
.replace(/ç/g, 'c')
.replace(/[^a-z0-9]/g, '-')
.replace(/-+/g, '-')
.replace(/^-|-$/g, '')
const { error } = await supabaseAdmin.from('categories').insert({
name: data.name,
slug: slug,
description: data.description,
image_url: data.image_url
})
if (error) return { error: "Kategori oluşturulamadı: " + error.message }
revalidatePath("/dashboard/categories")
return { success: true }
}
export async function updateCategory(id: string, data: { name: string, description?: string, image_url?: string }) {
const supabase = createClient()
// Check admin
const { data: { user } } = await supabase.auth.getUser()
if (!user) return { error: "Oturum açmanız gerekiyor." }
// Check if current user is admin
const { data: profile } = await supabase.from('profiles').select('role').eq('id', user.id).single()
if (profile?.role !== 'admin') return { error: "Yetkisiz işlem." }
const slug = data.name.toLowerCase()
.replace(/ğ/g, 'g')
.replace(/ü/g, 'u')
.replace(/ş/g, 's')
.replace(/ı/g, 'i')
.replace(/ö/g, 'o')
.replace(/ç/g, 'c')
.replace(/[^a-z0-9]/g, '-')
.replace(/-+/g, '-')
.replace(/^-|-$/g, '')
const { error } = await supabaseAdmin.from('categories').update({
name: data.name,
slug: slug,
description: data.description,
image_url: data.image_url
}).eq('id', id)
if (error) return { error: "Kategori güncellenemedi: " + error.message }
revalidatePath("/dashboard/categories")
return { success: true }
}
export async function deleteCategory(id: string) {
const supabase = createClient()
// Check admin
const { data: { user } } = await supabase.auth.getUser()
if (!user) return { error: "Oturum açmanız gerekiyor." }
// Check if current user is admin
const { data: profile } = await supabase.from('profiles').select('role').eq('id', user.id).single()
if (profile?.role !== 'admin') return { error: "Yetkisiz işlem." }
const { error } = await supabaseAdmin.from('categories').delete().eq('id', id)
if (error) return { error: "Kategori silinemedi: " + error.message }
revalidatePath("/dashboard/categories")
return { success: true }
}

View File

@@ -0,0 +1,9 @@
import { CategoryForm } from "@/components/dashboard/category-form"
export default function NewCategoryPage() {
return (
<div className="flex-1 space-y-4 p-8 pt-6">
<CategoryForm />
</div>
)
}

View File

@@ -0,0 +1,78 @@
import { createClient } from "@/lib/supabase-server"
import { format } from "date-fns"
import { tr } from "date-fns/locale"
import Link from "next/link"
import { Plus } from "lucide-react"
import { Button } from "@/components/ui/button"
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table"
export default async function CategoriesPage() {
const supabase = createClient()
const { data: categories } = await supabase
.from('categories')
.select('*')
.order('created_at', { ascending: false })
return (
<div className="flex-1 space-y-4 p-8 pt-6">
<div className="flex items-center justify-between">
<div>
<h2 className="text-3xl font-bold tracking-tight">Kategoriler ({categories?.length || 0})</h2>
<p className="text-muted-foreground">
Sitenizdeki ürün kategorilerini yönetin.
</p>
</div>
<Link href="/dashboard/categories/new">
<Button>
<Plus className="mr-2 h-4 w-4" /> Yeni Ekle
</Button>
</Link>
</div>
<div className="rounded-md border p-4">
<Table>
<TableHeader>
<TableRow>
<TableHead>Ad</TableHead>
<TableHead>Slug</TableHead>
<TableHead>Oluşturulma Tarihi</TableHead>
<TableHead className="text-right">İşlemler</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{categories?.map((category) => (
<TableRow key={category.id}>
<TableCell className="font-medium">{category.name}</TableCell>
<TableCell>{category.slug}</TableCell>
<TableCell>
{format(new Date(category.created_at), "d MMMM yyyy", { locale: tr })}
</TableCell>
<TableCell className="text-right">
<Link href={`/dashboard/categories/${category.id}`}>
<Button variant="ghost" size="sm">
Düzenle
</Button>
</Link>
</TableCell>
</TableRow>
))}
{(!categories || categories.length === 0) && (
<TableRow>
<TableCell colSpan={4} className="h-24 text-center">
Kategori bulunamadı.
</TableCell>
</TableRow>
)}
</TableBody>
</Table>
</div>
</div>
)
}

View File

@@ -1,126 +1,126 @@
import { createClient } from "@/lib/supabase-server"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { DollarSign, ShoppingCart, Users, CreditCard } from "lucide-react"
import { DollarSign, ShoppingCart, Users, CreditCard, Package } from "lucide-react"
import Link from "next/link"
import { Button } from "@/components/ui/button"
export default async function DashboardPage() {
const supabase = createClient()
// Fetch real data
const { data: products } = await supabase
.from("products")
.select("*")
.order("created_at", { ascending: false })
const totalProducts = products?.length || 0
const totalValue = products?.reduce((acc, product) => acc + (Number(product.price) || 0), 0) || 0
const recentProducts = products?.slice(0, 5) || []
// Calculate unique categories
const categories = new Set(products?.map(p => p.category)).size
export default function DashboardPage() {
return (
<div className="flex-1 space-y-4">
<div className="flex-1 space-y-4 p-8 pt-6">
<div className="flex items-center justify-between space-y-2">
<h2 className="text-3xl font-bold tracking-tight">Genel Bakış</h2>
<div className="flex items-center space-x-2">
<Link href="/dashboard/products/new">
<Button>Ürün Ekle</Button>
</Link>
</div>
</div>
{/* Stats Grid */}
<div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">Toplam Gelir</CardTitle>
<CardTitle className="text-sm font-medium">Toplam Ürün Değeri</CardTitle>
<DollarSign className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">45,231.89</div>
<p className="text-xs text-muted-foreground">+20.1% geçen aya göre</p>
<div className="text-2xl font-bold">{totalValue.toLocaleString('tr-TR', { minimumFractionDigits: 2 })}</div>
<p className="text-xs text-muted-foreground">Stoktaki toplam varlık</p>
</CardContent>
</Card>
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">Abonelikler</CardTitle>
<CardTitle className="text-sm font-medium">Toplam Ürün</CardTitle>
<Package className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">{totalProducts}</div>
<p className="text-xs text-muted-foreground">Kayıtlı ürün sayısı</p>
</CardContent>
</Card>
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">Kategoriler</CardTitle>
<ShoppingCart className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">{categories}</div>
<p className="text-xs text-muted-foreground">Aktif kategori</p>
</CardContent>
</Card>
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">Son Güncelleme</CardTitle>
<Users className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">+2350</div>
<p className="text-xs text-muted-foreground">+180.1% geçen aya göre</p>
</CardContent>
</Card>
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">Satışlar</CardTitle>
<CreditCard className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">+12,234</div>
<p className="text-xs text-muted-foreground">+19% geçen aya göre</p>
</CardContent>
</Card>
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">Aktif Şimdi</CardTitle>
<Users className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">+573</div>
<p className="text-xs text-muted-foreground">+201 son bir saatte</p>
<div className="text-2xl font-bold">Şimdi</div>
<p className="text-xs text-muted-foreground">Canlı veri akışı</p>
</CardContent>
</Card>
</div>
<div className="grid gap-4 md:grid-cols-2 lg:grid-cols-7">
{/* Recent Sales / Activity */}
<Card className="col-span-4">
<CardHeader>
<CardTitle>Son Hareketler</CardTitle>
<CardTitle>Son Eklenen Ürünler</CardTitle>
<CardDescription>
Bu ay 265+ satış yaptınız.
En son eklenen {recentProducts.length} ürün.
</CardDescription>
</CardHeader>
<CardContent>
{/* Mock List */}
<div className="space-y-8">
<div className="flex items-center">
<div className="h-9 w-9 rounded-full bg-slate-100 flex items-center justify-center">
<span className="font-bold text-xs">OM</span>
{recentProducts.map((product) => (
<div key={product.id} className="flex items-center">
<div className="h-9 w-9 rounded-full bg-slate-100 flex items-center justify-center">
<span className="font-bold text-xs">{product.name.substring(0, 2).toUpperCase()}</span>
</div>
<div className="ml-4 space-y-1">
<p className="text-sm font-medium leading-none">{product.name}</p>
<p className="text-sm text-muted-foreground">{product.category}</p>
</div>
<div className="ml-auto font-medium">{Number(product.price).toLocaleString('tr-TR')}</div>
</div>
<div className="ml-4 space-y-1">
<p className="text-sm font-medium leading-none">Ozan Mehmet</p>
<p className="text-sm text-muted-foreground">ozan@email.com</p>
</div>
<div className="ml-auto font-medium">+1,999.00</div>
</div>
<div className="flex items-center">
<div className="h-9 w-9 rounded-full bg-slate-100 flex items-center justify-center">
<span className="font-bold text-xs"></span>
</div>
<div className="ml-4 space-y-1">
<p className="text-sm font-medium leading-none">Ayşe Özdemir</p>
<p className="text-sm text-muted-foreground">ayse@email.com</p>
</div>
<div className="ml-auto font-medium">+39.00</div>
</div>
<div className="flex items-center">
<div className="h-9 w-9 rounded-full bg-slate-100 flex items-center justify-center">
<span className="font-bold text-xs">MK</span>
</div>
<div className="ml-4 space-y-1">
<p className="text-sm font-medium leading-none">Mehmet Kaya</p>
<p className="text-sm text-muted-foreground">mehmet@email.com</p>
</div>
<div className="ml-auto font-medium">+299.00</div>
</div>
))}
{recentProducts.length === 0 && (
<div className="text-center py-4 text-muted-foreground">Henüz ürün yok.</div>
)}
</div>
</CardContent>
</Card>
{/* Recent Products or Other Info */}
{/* Placeholder for future features or quick actions */}
<Card className="col-span-3">
<CardHeader>
<CardTitle>Son Eklenen Ürünler</CardTitle>
<CardTitle>Hızlı İşlemler</CardTitle>
<CardDescription>
Stoğa yeni giren ürünler.
Yönetim paneli kısayolları.
</CardDescription>
</CardHeader>
<CardContent>
<div className="space-y-4">
<div className="flex justify-between items-center bg-slate-50 p-2 rounded">
<span className="text-sm font-medium">Çelik Kasa EV-100</span>
<span className="text-xs bg-green-100 text-green-700 px-2 py-1 rounded">Stokta</span>
</div>
<div className="flex justify-between items-center bg-slate-50 p-2 rounded">
<span className="text-sm font-medium">Ofis Tipi XYZ</span>
<span className="text-xs bg-yellow-100 text-yellow-700 px-2 py-1 rounded">Azaldı</span>
</div>
<div className="flex justify-between items-center bg-slate-50 p-2 rounded">
<span className="text-sm font-medium">Otel Kasası H-20</span>
<span className="text-xs bg-green-100 text-green-700 px-2 py-1 rounded">Stokta</span>
</div>
<div className="flex flex-col space-y-2">
<Link href="/dashboard/products/new">
<Button variant="outline" className="w-full justify-start">
<PlusIcon className="mr-2 h-4 w-4" /> Yeni Ürün Ekle
</Button>
</Link>
<Button variant="outline" className="w-full justify-start" disabled>
<ShoppingCart className="mr-2 h-4 w-4" /> Siparişleri Yönet (Yakında)
</Button>
</div>
</CardContent>
</Card>
@@ -128,3 +128,23 @@ export default function DashboardPage() {
</div>
)
}
function PlusIcon(props: any) {
return (
<svg
{...props}
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
>
<path d="M5 12h14" />
<path d="M12 5v14" />
</svg>
)
}

View File

@@ -0,0 +1,33 @@
import { createClient } from "@/lib/supabase-server"
import { ProductForm } from "@/components/dashboard/product-form"
import { notFound } from "next/navigation"
interface ProductEditPageProps {
params: {
productId: string
}
}
export default async function ProductEditPage({ params }: ProductEditPageProps) {
const supabase = createClient()
const { data: product } = await supabase
.from("products")
.select("*")
.eq("id", params.productId)
.single()
if (!product) {
notFound()
}
return (
<div className="flex-1 space-y-4 p-8 pt-6">
<div className="flex items-center justify-between">
<h2 className="text-3xl font-bold tracking-tight">Ürün Düzenle</h2>
</div>
<div className="max-w-2xl">
<ProductForm initialData={product} />
</div>
</div>
)
}

View File

@@ -0,0 +1,51 @@
"use server"
import { createClient } from "@/lib/supabase-server"
import { revalidatePath } from "next/cache"
export async function createProduct(data: any) {
const supabase = createClient()
// Validate data manually or use Zod schema here again securely
// For simplicity, we assume data is coming from the strongly typed Client Form
// In production, ALWAYS validate server-side strictly.
try {
const { error } = await supabase.from("products").insert({
name: data.name,
category: data.category,
description: data.description,
price: data.price,
image_url: data.image_url,
})
if (error) throw error
revalidatePath("/dashboard/products")
return { success: true }
} catch (error: any) {
return { success: false, error: error.message }
}
}
export async function updateProduct(id: number, data: any) {
const supabase = createClient()
try {
const { error } = await supabase.from("products").update({
name: data.name,
category: data.category,
description: data.description,
price: data.price,
image_url: data.image_url,
}).eq("id", id)
if (error) throw error
revalidatePath("/dashboard/products")
revalidatePath(`/dashboard/products/${id}`)
return { success: true }
} catch (error: any) {
return { success: false, error: error.message }
}
}

View File

@@ -0,0 +1,14 @@
import { ProductForm } from "@/components/dashboard/product-form"
export default function NewProductPage() {
return (
<div className="flex-1 space-y-4 p-8 pt-6">
<div className="flex items-center justify-between">
<h2 className="text-3xl font-bold tracking-tight">Yeni Ürün Ekle</h2>
</div>
<div className="max-w-2xl">
<ProductForm />
</div>
</div>
)
}

View File

@@ -0,0 +1,75 @@
import { createClient } from "@/lib/supabase-server"
import { Button } from "@/components/ui/button"
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table"
import { Plus } from "lucide-react"
import Link from "next/link"
import { Badge } from "@/components/ui/badge"
export default async function ProductsPage() {
const supabase = createClient()
const { data: products } = await supabase
.from("products")
.select("*")
.order("created_at", { ascending: false })
return (
<div className="flex-1 space-y-4 p-8 pt-6">
<div className="flex items-center justify-between">
<h2 className="text-3xl font-bold tracking-tight">Ürünler</h2>
<div className="flex items-center space-x-2">
<Link href="/dashboard/products/new">
<Button>
<Plus className="mr-2 h-4 w-4" /> Yeni Ekle
</Button>
</Link>
</div>
</div>
<div className="border rounded-md">
<Table>
<TableHeader>
<TableRow>
<TableHead>Ad</TableHead>
<TableHead>Kategori</TableHead>
<TableHead>Fiyat</TableHead>
<TableHead className="text-right">İşlemler</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{products?.length === 0 ? (
<TableRow>
<TableCell colSpan={4} className="h-24 text-center">
Henüz ürün eklenmemiş.
</TableCell>
</TableRow>
) : (
products?.map((product) => (
<TableRow key={product.id}>
<TableCell className="font-medium">{product.name}</TableCell>
<TableCell>
<Badge variant="secondary" className="capitalize">
{product.category}
</Badge>
</TableCell>
<TableCell>{product.price}</TableCell>
<TableCell className="text-right">
<Link href={`/dashboard/products/${product.id}`}>
<Button variant="ghost" size="sm">Düzenle</Button>
</Link>
</TableCell>
</TableRow>
))
)}
</TableBody>
</Table>
</div>
</div>
)
}

View File

@@ -0,0 +1,50 @@
import { createClient } from "@/lib/supabase-server"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
export default async function ProfilePage() {
const supabase = createClient()
const { data: { user } } = await supabase.auth.getUser()
return (
<div className="flex-1 space-y-4 p-8 pt-6">
<div className="flex items-center justify-between space-y-2">
<h2 className="text-3xl font-bold tracking-tight">Profil</h2>
</div>
<div className="grid gap-4 md:grid-cols-2">
<Card>
<CardHeader>
<CardTitle>Genel Bilgiler</CardTitle>
<CardDescription>
Kişisel profil bilgileriniz.
</CardDescription>
</CardHeader>
<CardContent className="space-y-6">
<div className="flex items-center space-x-4">
<Avatar className="h-20 w-20">
<AvatarImage src="/avatars/01.png" alt="@parakasa" />
<AvatarFallback>PK</AvatarFallback>
</Avatar>
<Button variant="outline">Fotoğraf Değiştir</Button>
</div>
<div className="space-y-1">
<Label htmlFor="email">E-posta</Label>
<Input id="email" value={user?.email || ""} disabled />
<p className="text-xs text-muted-foreground">E-posta adresi değiştirilemez.</p>
</div>
<div className="space-y-1">
<Label htmlFor="role">Rol</Label>
<Input id="role" value={user?.role === 'authenticated' ? 'Yönetici' : 'Kullanıcı'} disabled />
</div>
</CardContent>
</Card>
</div>
</div>
)
}

View File

@@ -0,0 +1,42 @@
"use server"
import { createClient } from "@/lib/supabase-server"
import { revalidatePath } from "next/cache"
export async function updateSiteSettings(data: {
site_title: string
site_description: string
contact_email: string
contact_phone: string
currency: string
}) {
const supabase = createClient()
// Check admin is already handled by RLS on database level, but we can double check here
const { data: { user } } = await supabase.auth.getUser()
if (!user) return { error: "Oturum açmanız gerekiyor." }
// We update the single row where id is likely 1 or just the first row
// Since we initialized it with one row, we can just update match on something true or fetch id first.
// Easier: Update all rows (there should only be one) or fetch the specific ID first.
// Let's first get the ID just to be precise
const { data: existing } = await supabase.from('site_settings').select('id').single()
if (!existing) {
return { error: "Ayarlar bulunamadı." }
}
const { error } = await supabase
.from('site_settings')
.update(data)
.eq('id', existing.id)
if (error) {
return { error: "Ayarlar güncellenemedi: " + error.message }
}
revalidatePath("/dashboard/settings")
revalidatePath("/") // Revalidate home as it might use these settings
return { success: true }
}

View File

@@ -0,0 +1,45 @@
import { createClient } from "@/lib/supabase-server"
import { SiteSettingsForm } from "@/components/dashboard/site-settings-form"
import { AppearanceForm } from "@/components/dashboard/appearance-form"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Label } from "@/components/ui/label"
import { Switch } from "@/components/ui/switch"
import { Button } from "@/components/ui/button"
export default async function SettingsPage() {
const supabase = createClient()
// Fetch site settings
const { data: settings } = await supabase
.from('site_settings')
.select('*')
.single()
return (
<div className="flex-1 space-y-4 p-8 pt-6">
<h2 className="text-3xl font-bold tracking-tight">Ayarlar</h2>
{/* Site General Settings */}
<div className="grid gap-4">
<SiteSettingsForm initialData={settings} />
</div>
<div className="grid gap-4 grid-cols-1 md:grid-cols-2">
<AppearanceForm />
<Card>
<CardHeader>
<CardTitle>Hesap Güvenliği</CardTitle>
<CardDescription>
Şifre ve oturum yönetimi.
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<Button variant="outline" className="w-full">Şifre Değiştir</Button>
<Button variant="destructive" className="w-full">Hesabı Sil</Button>
</CardContent>
</Card>
</div>
</div>
)
}

View File

@@ -0,0 +1,69 @@
import { createClient } from "@/lib/supabase-server"
import { UserForm } from "@/components/dashboard/user-form"
import { notFound } from "next/navigation"
export default async function EditUserPage({ params }: { params: { userId: string } }) {
const supabase = createClient()
// Fetch profile
const { data: profile } = await supabase
.from('profiles')
.select('*')
.eq('id', params.userId)
.single()
if (!profile) {
notFound()
}
// We also need the email, which is in auth.users, but we can't select from there easily with RLS/Client if not admin API
// However, our logged in user IS admin, but RLS on auth.users is usually strict.
// Let's see if we can get it via RPC or if the profile should store email (bad practice duplication, but helpful).
// Actually, `supabaseAdmin` in a server action can get it, but here we are in a Page (Server Component).
// We can use `supabaseAdmin` here too if we create a utility for it or just import createClient from supabase-js with admin key.
// WORKAROUND: For now, let's assume we might need a server function to fetch full user details including email
// OR we just update the profile part. But the user wants to update email probably.
// Let's write a small server action/function to fetch this data securely to render the form.
// Better: Helper function to get user details
const userDetails = await getUserDetails(params.userId)
return (
<div className="flex-1 space-y-4 p-8 pt-6">
<div className="flex items-center justify-between space-y-2">
<h2 className="text-3xl font-bold tracking-tight">Kullanıcı Düzenle</h2>
</div>
<UserForm initialData={userDetails} />
</div>
)
}
// Helper to get admin-level data for the form
import { createClient as createSupabaseClient } from "@supabase/supabase-js"
async function getUserDetails(userId: string) {
const supabaseAdmin = createSupabaseClient(
process.env.NEXT_PUBLIC_SUPABASE_URL!,
process.env.SUPABASE_SERVICE_ROLE_KEY!,
{ auth: { autoRefreshToken: false, persistSession: false } }
)
const { data: { user }, error } = await supabaseAdmin.auth.admin.getUserById(userId)
const { data: profile } = await supabaseAdmin.from('profiles').select('*').eq('id', userId).single()
if (error || !user || !profile) return undefined
// Split full name
const parts = (profile.full_name || "").split(' ')
const firstName = parts[0] || ""
const lastName = parts.slice(1).join(' ') || ""
return {
id: userId,
firstName,
lastName,
email: user.email || "",
role: profile.role as "admin" | "user"
}
}

View File

@@ -0,0 +1,133 @@
"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') {
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
})
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' }) {
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
})
.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 }
}

View File

@@ -0,0 +1,13 @@
import { UserForm } from "@/components/dashboard/user-form"
export default function NewUserPage() {
return (
<div className="flex-1 space-y-4 p-8 pt-6">
<div className="flex items-center justify-between space-y-2">
<h2 className="text-3xl font-bold tracking-tight">Yeni Kullanıcı Ekle</h2>
</div>
<UserForm />
</div>
)
}

View File

@@ -0,0 +1,87 @@
import { createClient } from "@/lib/supabase-server"
import { Button } from "@/components/ui/button"
import Link from "next/link"
import { Plus } from "lucide-react"
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table"
import { Badge } from "@/components/ui/badge"
export default async function UsersPage() {
const supabase = createClient()
const { data: { user } } = await supabase.auth.getUser()
// Protected Route Check (Simple)
const { data: currentUserProfile } = await supabase
.from('profiles')
.select('role')
.eq('id', user?.id)
.single()
// Only verify if we have profiles, if not (first run), maybe allow?
// But for safety, blocking non-admins.
if (currentUserProfile?.role !== 'admin') {
return (
<div className="flex-1 p-8 pt-6">
<h2 className="text-3xl font-bold tracking-tight text-red-600">Yetkisiz Erişim</h2>
<p>Bu sayfayı görüntüleme yetkiniz yok.</p>
</div>
)
}
const { data: profiles } = await supabase
.from("profiles")
.select("*")
.order("created_at", { ascending: false })
return (
<div className="flex-1 space-y-4 p-8 pt-6">
<div className="flex items-center justify-between space-y-2">
<h2 className="text-3xl font-bold tracking-tight">Kullanıcı Yönetimi</h2>
<div className="flex items-center space-x-2">
<Link href="/dashboard/users/new">
<Button>
<Plus className="mr-2 h-4 w-4" /> Yeni Kullanıcı
</Button>
</Link>
</div>
</div>
<div className="rounded-md border">
<Table>
<TableHeader>
<TableRow>
<TableHead>Ad Soyad</TableHead>
<TableHead>Rol</TableHead>
<TableHead>Kayıt Tarihi</TableHead>
<TableHead className="text-right">İşlemler</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{profiles?.map((profile) => (
<TableRow key={profile.id}>
<TableCell className="font-medium">{profile.full_name}</TableCell>
<TableCell>
<Badge variant={profile.role === 'admin' ? 'default' : 'secondary'}>
{profile.role === 'admin' ? 'Yönetici' : 'Kullanıcı'}
</Badge>
</TableCell>
<TableCell>{new Date(profile.created_at).toLocaleDateString('tr-TR')}</TableCell>
<TableCell className="text-right">
<Link href={`/dashboard/users/${profile.id}`}>
<Button variant="ghost" size="sm">Düzenle</Button>
</Link>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</div>
</div>
)
}