import { MissingPrivileges } from '../types' ; import { useAuthorizationContext } from './authorization_provider' ; interface Props { /**
     * Each required privilege must have the format "section.privilege".
     * To indicate that *all* privileges from a section are required, we can use the asterix
     * e.g. "index.*"
     */ privileges : string | string [ ] ; children : ( childrenProps : { isLoading : boolean ; hasPrivileges : boolean ; privilegesMissing : MissingPrivileges ; } ) => JSX . Element ; } type Privilege = [ string , string ] ; const toArray = ( value ) : string [ ] => Array . isArray ( value ) ? ( value as string [ ] ) : ( [ value ] as string [ ] ) ; export const WithPrivileges = ( { privileges : requiredPrivileges , children } ) => { const { isLoading , privileges } = useAuthorizationContext ( ) ; const privilegesToArray = toArray ( requiredPrivileges ) . map ( ( p ) => { const [ section , privilege ] = p . split ( '.' ) ; if ( ! privilege ) { throw new Error ( 'Required privilege must have the format "section.privilege"' ) ; } return [ section , privilege ] ; } ) ; const hasPrivileges = isLoading ? false : privilegesToArray . every ( ( privilege ) => { const [ section , requiredPrivilege ] = privilege ; if ( ! privileges . missingPrivileges [ section ] ) { return true ; } if ( privileges . missingPrivileges [ section ] ! . length === 0 ) { return true ; } if ( requiredPrivilege === '*' ) { return false ; } return ! privileges . missingPrivileges [ section ] ! . includes ( requiredPrivilege ) ; } ) ; const privilegesMissing = privilegesToArray . reduce ( ( acc , [ section , privilege ] ) => { if ( privilege === '*' ) { acc [ section ] = privileges . missingPrivileges [ section ] || [ ] ; } else if ( privileges . missingPrivileges [ section ] && privileges . missingPrivileges [ section ] ! . includes ( privilege ) ) { const missing = acc [ section ] || [ ] ; acc [ section ] = [ ... missing , privilege ] ; } return acc ; } , { } as MissingPrivileges ) ; return children ( { isLoading , hasPrivileges , privilegesMissing } ) ; } ;