Files
kvm/src/composables/useAuth.js
T
2026-02-12 15:40:10 +08:00

55 lines
1.1 KiB
JavaScript

import { computed } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/userStore'
/**
* 认证相关组合式函数
*/
export function useAuth() {
const router = useRouter()
const userStore = useUserStore()
const isAuthenticated = computed(() => userStore.isAuthenticated)
const isAdmin = computed(() => userStore.isAdmin)
const currentUser = computed(() => userStore.user)
// 检查权限
const checkPermission = (requiredRole) => {
if (requiredRole === 'admin' && !isAdmin.value) {
return false
}
return true
}
// 需要登录
const requireAuth = () => {
if (!isAuthenticated.value) {
router.push('/login')
return false
}
return true
}
// 需要管理员权限
const requireAdmin = () => {
if (!isAuthenticated.value) {
router.push('/login')
return false
}
if (!isAdmin.value) {
router.push('/dashboard')
return false
}
return true
}
return {
isAuthenticated,
isAdmin,
currentUser,
checkPermission,
requireAuth,
requireAdmin
}
}