usePermission.ts
2.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import type { AuthUser } from '~/types'
import type { ButtonPermissionKey } from '~/utils/permission'
import { createSharedComposable } from '@vueuse/core'
import {
APP_PAGE_PATHS,
canAccessPageByRoles,
canUseButtonByRoles,
getAccessiblePagesForRoles,
isProtectedPage,
normalizePagePath,
toPagePath
} from '~/utils/permission'
function toRoles(user: AuthUser | null) {
if (!user || !Array.isArray(user.roles)) {
return []
}
return user.roles.filter(role => typeof role === 'string' && role.trim().length > 0)
}
const _usePermission = () => {
const route = useRoute()
const { user } = useAuth()
const roles = computed(() => toRoles(user.value))
const allowedPages = computed(() => getAccessiblePagesForRoles(roles.value))
const canAccessPage = (pagePath: string) => {
return canAccessPageByRoles(roles.value, pagePath)
}
const can = (pagePath: string, buttonKey: ButtonPermissionKey) => {
return canUseButtonByRoles(roles.value, pagePath, buttonKey)
}
const canInCurrentPage = (buttonKey: ButtonPermissionKey) => {
return can(route.path, buttonKey)
}
const isAllowedPage = (pagePath: string) => {
const pageKey = toPagePath(pagePath)
if (!pageKey) {
return false
}
return allowedPages.value.has(pageKey)
}
const getAllowedPages = () => {
return APP_PAGE_PATHS.filter(pagePath => allowedPages.value.has(pagePath))
}
const getDeniedReason = (pagePath: string, buttonKey?: ButtonPermissionKey) => {
if (!isProtectedPage(pagePath)) {
return 'permission.pageNotManaged'
}
if (!canAccessPage(pagePath)) {
return 'permission.pageDenied'
}
if (buttonKey && !can(pagePath, buttonKey)) {
return 'permission.buttonDenied'
}
return 'permission.denied'
}
const normalize = (pagePath: string) => normalizePagePath(pagePath)
return {
roles,
allowedPages,
canAccessPage,
can,
canInCurrentPage,
isAllowedPage,
getAllowedPages,
getDeniedReason,
normalize
}
}
export const usePermission = createSharedComposable(_usePermission)