|
|
@ -2,19 +2,19 @@ import { isString } from '@vueuse/core' |
|
|
|
import type { Permission } from './rolePermissions' |
|
|
|
import type { Permission } from './rolePermissions' |
|
|
|
import rolePermissions from './rolePermissions' |
|
|
|
import rolePermissions from './rolePermissions' |
|
|
|
import { USER_PROJECT_ROLES, computed, useGlobal, useState } from '#imports' |
|
|
|
import { USER_PROJECT_ROLES, computed, useGlobal, useState } from '#imports' |
|
|
|
import type { Role, Roles } from '~/lib' |
|
|
|
import type { Roles } from '~/lib' |
|
|
|
|
|
|
|
|
|
|
|
export function useUIPermission() { |
|
|
|
export function useUIPermission() { |
|
|
|
const { user, previewAs } = useGlobal() |
|
|
|
const { user, previewAs } = useGlobal() |
|
|
|
|
|
|
|
|
|
|
|
const projectRoles = useState<Record<string, boolean>>(USER_PROJECT_ROLES, () => ({})) |
|
|
|
const projectRoles = useState<Roles>(USER_PROJECT_ROLES, () => ({})) |
|
|
|
|
|
|
|
|
|
|
|
const baseRoles = computed(() => { |
|
|
|
const baseRoles = computed<Roles>(() => { |
|
|
|
let userRoles = isString(user.value?.roles) ? user.value?.roles : ({ ...(user.value?.roles || {}) } as Roles) |
|
|
|
let userRoles = user.value?.roles |
|
|
|
|
|
|
|
|
|
|
|
// if string populate key-value paired object
|
|
|
|
// if string populate key-value paired object
|
|
|
|
if (typeof userRoles === 'string') { |
|
|
|
if (isString(userRoles)) { |
|
|
|
userRoles = userRoles.split(',').reduce<Record<string, boolean>>((acc, role) => { |
|
|
|
userRoles = userRoles.split(',').reduce<Roles>((acc, role) => { |
|
|
|
acc[role] = true |
|
|
|
acc[role] = true |
|
|
|
return acc |
|
|
|
return acc |
|
|
|
}, {}) |
|
|
|
}, {}) |
|
|
@ -27,18 +27,19 @@ export function useUIPermission() { |
|
|
|
} |
|
|
|
} |
|
|
|
}) |
|
|
|
}) |
|
|
|
|
|
|
|
|
|
|
|
const isUIAllowed = (permission: Permission | string, skipPreviewAs = false) => { |
|
|
|
const isUIAllowed = (permission: Permission, skipPreviewAs = false) => { |
|
|
|
let roles = baseRoles.value as Record<string, any> |
|
|
|
let roles = baseRoles.value |
|
|
|
|
|
|
|
|
|
|
|
if (previewAs.value && !skipPreviewAs) { |
|
|
|
if (previewAs.value && !skipPreviewAs) { |
|
|
|
roles = { |
|
|
|
roles = { |
|
|
|
[previewAs.value as Role]: true, |
|
|
|
[previewAs.value]: true, |
|
|
|
} |
|
|
|
} |
|
|
|
} |
|
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
return Object.entries<boolean>(roles).some(([role, hasRole]) => { |
|
|
|
return Object.entries(roles).some(([role, hasRole]) => { |
|
|
|
const rolePermission = rolePermissions[role as keyof typeof rolePermissions] as '*' | Record<Permission, true> |
|
|
|
const rolePermission = rolePermissions[role as keyof typeof rolePermissions] |
|
|
|
return hasRole && (rolePermission === '*' || rolePermission?.[permission as Permission]) |
|
|
|
|
|
|
|
|
|
|
|
return hasRole && (rolePermission === '*' || rolePermission?.[permission as keyof typeof rolePermission]) |
|
|
|
}) |
|
|
|
}) |
|
|
|
} |
|
|
|
} |
|
|
|
|
|
|
|
|
|
|
|