Files
sgse-app/apps/web/src/lib/components/ProtectedRoute.svelte
killer-cf 9a5f2b294d refactor: integrate current user data across components
- Replaced instances of `authStore` with `currentUser` to streamline user authentication handling.
- Updated permission checks and user-related data retrieval to utilize the new `useQuery` for better performance and clarity.
- Cleaned up component structures and improved formatting for consistency and readability.
- Enhanced error handling and user feedback mechanisms in various components to improve user experience.
2025-11-08 10:52:33 -03:00

81 lines
2.2 KiB
Svelte

<script lang="ts">
import { useQuery } from "convex-svelte";
import { api } from "@sgse-app/backend/convex/_generated/api";
import { onMount } from "svelte";
import { page } from "$app/stores";
import type { Snippet } from "svelte";
let {
children,
requireAuth = true,
allowedRoles = [],
maxLevel = 3,
redirectTo = "/",
}: {
children: Snippet;
requireAuth?: boolean;
allowedRoles?: string[];
maxLevel?: number;
redirectTo?: string;
} = $props();
let isChecking = $state(true);
let hasAccess = $state(false);
const currentUser = useQuery(api.auth.getCurrentUser, {});
onMount(() => {
checkAccess();
});
function checkAccess() {
isChecking = true;
// Aguardar um pouco para o authStore carregar do localStorage
setTimeout(() => {
// Verificar autenticação
if (requireAuth && !currentUser?.data) {
const currentPath = window.location.pathname;
window.location.href = `${redirectTo}?error=auth_required&redirect=${encodeURIComponent(currentPath)}`;
return;
}
// Verificar roles
if (allowedRoles.length > 0 && currentUser?.data) {
const hasRole = allowedRoles.includes(
currentUser.data.role?.nome ?? "",
);
if (!hasRole) {
const currentPath = window.location.pathname;
window.location.href = `${redirectTo}?error=access_denied&route=${encodeURIComponent(currentPath)}`;
return;
}
}
// Verificar nível
if (
currentUser?.data &&
currentUser.data.role?.nivel &&
currentUser.data.role.nivel > maxLevel
) {
const currentPath = window.location.pathname;
window.location.href = `${redirectTo}?error=access_denied&route=${encodeURIComponent(currentPath)}`;
return;
}
hasAccess = true;
isChecking = false;
}, 100);
}
</script>
{#if isChecking}
<div class="flex justify-center items-center min-h-screen">
<div class="text-center">
<span class="loading loading-spinner loading-lg text-primary"></span>
<p class="mt-4 text-base-content/70">Verificando permissões...</p>
</div>
</div>
{:else if hasAccess}
{@render children()}
{/if}