Files
classroomio/apps/dashboard/src/lib/features/ui/role-based-security.svelte
T

44 lines
1.2 KiB
Svelte
Raw Normal View History

2021-09-11 21:52:46 +03:00
<script lang="ts">
import { profile } from '$lib/utils/store/user';
2026-03-09 11:18:22 +01:00
import { courseApi } from '$features/course/api';
2024-07-08 06:52:23 +01:00
import { isOrgAdmin } from '$lib/utils/store/org';
2021-09-11 21:52:46 +03:00
2025-11-01 15:49:29 +01:00
interface Props {
allowedRoles?: number[];
onDenied?: any;
// Since orgAdmin can see all, we need a way to show the content only to students
onlyStudent?: boolean;
children?: import('svelte').Snippet;
}
2021-09-11 21:52:46 +03:00
2025-11-01 15:49:29 +01:00
let { allowedRoles = [], onDenied = () => {}, onlyStudent = false, children }: Props = $props();
2026-03-09 11:18:22 +01:00
const userRole: number | null = $derived.by(() => {
const user = courseApi.group.people.find((person) => person.profileId === $profile.id);
return user ? Number(user.roleId) : null;
2025-11-01 15:49:29 +01:00
});
const show = $derived.by(() => {
if (onlyStudent) {
return isAllowed(userRole);
} else {
return isAllowed(userRole) || !!$isOrgAdmin;
}
});
2021-09-11 21:52:46 +03:00
2026-03-09 11:18:22 +01:00
function isAllowed(userRole: number | null) {
if (userRole === null) return false;
2024-07-21 03:02:33 +01:00
return allowedRoles.includes(userRole);
}
2025-11-01 15:49:29 +01:00
$effect(() => {
2026-03-09 11:18:22 +01:00
if (!$isOrgAdmin && userRole !== null && !isAllowed(userRole)) {
onDenied();
}
2025-11-01 15:49:29 +01:00
});
2021-09-11 21:52:46 +03:00
</script>
2024-07-21 03:02:33 +01:00
{#if show}
2025-11-01 15:49:29 +01:00
{@render children?.()}
2021-09-11 21:52:46 +03:00
{/if}