All files / js/components PermissionGuard.vue

0% Statements 0/16
0% Branches 0/16
0% Functions 0/2
0% Lines 0/16

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                                                                                                                                             
<script setup lang="ts">
import { computed } from 'vue';
import { usePermissionError } from '@/composables/usePermissionError';
 
interface Props {
    module: string;
    ability: string;
    fallback?: 'modal' | 'hide' | 'disable';
}
 
const props = withDefaults(defineProps<Props>(), {
    fallback: 'modal',
});
 
const { showError } = usePermissionError();
 
// Get the current page props to check abilities
const page = (window as any).$page;
const hasPermission = computed(() => {
    if (!page?.props?.auth?.abilities) {
        return false;
    }
 
    const moduleAbilities = page.props.auth.abilities[props.module];
    if (!moduleAbilities) {
        return false;
    }
 
    return !!moduleAbilities[props.ability];
});
 
function handleClick(event: Event) {
    if (!hasPermission.value) {
        event.preventDefault();
        event.stopPropagation();
        
        if (props.fallback === 'modal') {
            showError({
                module: props.module,
                ability: props.ability,
                message: `You don't have permission to ${props.ability} ${props.module}.`,
            });
        }
    }
}
</script>
 
<template>
    <div
        v-if="fallback === 'hide' && !hasPermission"
        style="display: none;"
    >
        <slot />
    </div>
    
    <div
        v-else-if="fallback === 'disable' && !hasPermission"
        class="opacity-50 cursor-not-allowed"
        @click="handleClick"
    >
        <slot />
    </div>
    
    <div
        v-else
        @click="handleClick"
    >
        <slot />
    </div>
</template>