// Middleware สำหรับตรวจสอบสิทธิ์การเข้าถึงหน้าเว็บ (Authentication Guard) export default defineNuxtRouteMiddleware((to) => { const { isAuthenticated, user } = useAuth() // รายชื่อหน้าสำหรับ Guest (ห้าม User ที่ Login แล้วเข้า) // เช่น หน้า Login, Register const authPages = [ '/auth/login', '/auth/register', '/auth/forgot-password', '/auth/reset-password' ] // รายชื่อหน้าที่เข้าถึงได้โดยไม่ต้อง Login (Public Pages) const publicPages = ['/', '/courses', '/browse', '/browse/discovery'] // กรณีที่ 1: ผู้ใช้ Login แล้ว แต่พยายามเข้าหน้า Login/Register // ระบบจะดีดกลับไปหน้า Dashboard ตาม Role ของผู้ใช้ if (isAuthenticated.value && authPages.includes(to.path)) { const role = user.value?.role?.code if (role === 'ADMIN') return navigateTo('/admin', { replace: true }) if (role === 'INSTRUCTOR') return navigateTo('/instructor', { replace: true }) return navigateTo('/dashboard', { replace: true }) } // กรณีที่ 2: ผู้ใช้ยังไม่ Login แต่พยายามเข้าหน้าที่ต้อง Login (Protected Pages) // (หน้าอื่น ๆ ที่ไม่ได้อยู่ใน publicPages และ authPages) if (!isAuthenticated.value && !authPages.includes(to.path) && !publicPages.includes(to.path)) { return navigateTo('/auth/login', { replace: true }) } })