feat(FE) : implementasi hak akses
This commit is contained in:
No files matched your search
@@ -0,0 +1,74 @@
|
||||
import { useUserMenuStore } from '~/store/userMenu'
|
||||
|
||||
export const useUserMenu = () => {
|
||||
const menuStore = useUserMenuStore()
|
||||
const { user } = useAuth()
|
||||
|
||||
const initializeMenu = async () => {
|
||||
// Get token from localStorage (client-side only)
|
||||
if (!process.client) {
|
||||
return
|
||||
}
|
||||
|
||||
// Skip if menu already fetched (even if empty/no access)
|
||||
if (menuStore.menuFetched) {
|
||||
console.log('ℹ️ Menu already fetched, skipping re-fetch')
|
||||
return
|
||||
}
|
||||
|
||||
// Check if user ID is available
|
||||
if (!user.value?.id) {
|
||||
console.warn('⚠️ Cannot fetch menu: User ID not available')
|
||||
return
|
||||
}
|
||||
|
||||
const token = localStorage.getItem('idToken')
|
||||
if (!token) {
|
||||
console.warn('⚠️ Cannot fetch menu: No token available in localStorage')
|
||||
return
|
||||
}
|
||||
|
||||
// Use actual user ID from auth
|
||||
const userIdToUse = user.value.id
|
||||
|
||||
try {
|
||||
await menuStore.fetchUserMenu(userIdToUse, token)
|
||||
} catch (error) {
|
||||
console.error('❌ Error initializing menu:', error)
|
||||
}
|
||||
}
|
||||
|
||||
const refreshMenu = async () => {
|
||||
if (!user.value?.id || !process.client) return
|
||||
|
||||
const token = localStorage.getItem('idToken')
|
||||
if (!token) return
|
||||
|
||||
await menuStore.fetchUserMenu(user.value.id, token)
|
||||
}
|
||||
|
||||
// Watch for user changes and auto-initialize menu
|
||||
if (process.client) {
|
||||
// Watch for user.id to become available
|
||||
watchEffect(async () => {
|
||||
const userId = user.value?.id
|
||||
const hasToken = !!localStorage.getItem('idToken')
|
||||
|
||||
// Initialize if user ID and token exist, and menu not fetched yet
|
||||
if (userId && hasToken && !menuStore.menuFetched && !menuStore.isLoading) {
|
||||
await initializeMenu()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
return {
|
||||
menuStore,
|
||||
menuItems: computed(() => menuStore.sidebarMenuItems),
|
||||
hasMenu: computed(() => menuStore.hasMenu),
|
||||
isLoading: computed(() => menuStore.isLoading),
|
||||
error: computed(() => menuStore.error),
|
||||
noAccess: computed(() => menuStore.noAccess),
|
||||
initializeMenu,
|
||||
refreshMenu
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user