Browse Source

refactor(nc-gui): use injection state for `useUIPermission`

pull/3703/head
braks 2 years ago
parent
commit
84b9f8b10f
  1. 44
      packages/nc-gui/composables/useUIPermission/index.ts

44
packages/nc-gui/composables/useUIPermission/index.ts

@ -1,33 +1,13 @@
import { isString } from '@vueuse/core' 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 { useGlobal, useInjectionState, useRoles } from '#imports'
import type { ProjectRole, Role, Roles } from '~/lib' import type { ProjectRole, Role } from '~/lib'
export function useUIPermission() { const [setup, use] = useInjectionState(() => {
const { user, previewAs } = useGlobal() const { previewAs } = useGlobal()
const projectRoles = useState<Roles<ProjectRole>>(USER_PROJECT_ROLES, () => ({})) const { allRoles } = useRoles()
const allRoles = useState<Roles>('allRoles', () =>
computed(() => {
let userRoles = user.value?.roles
// if string populate key-value paired object
if (isString(userRoles)) {
userRoles = userRoles.split(',').reduce<Roles>((acc, role) => {
acc[role] = true
return acc
}, {})
}
// merge user role and project specific user roles
return {
...userRoles,
...projectRoles.value,
}
}),
)
const hasPermission = (role: Role | ProjectRole, hasRole: boolean, permission: Permission | string) => { const hasPermission = (role: Role | ProjectRole, hasRole: boolean, permission: Permission | string) => {
const rolePermission = rolePermissions[role] const rolePermission = rolePermissions[role]
@ -51,5 +31,15 @@ export function useUIPermission() {
) )
} }
return { isUIAllowed } return { isUIAllowed, projectRoles }
}, 'useUIPermission')
export function useUIPermission() {
let usePermissions = use()
if (!usePermissions) {
usePermissions = setup()
}
return { isUIAllowed: usePermissions.isUIAllowed }
} }

Loading…
Cancel
Save