forge
Explore
Log in

Don't you dare go Hollow

hezarfen_frontend

Clone
★ 0

0 watching0 forksTypeScript5.5 MiB5fcd955Burak Boduroğlu2 months ago730 commits

route-guard.tsx123 lines, 5.4 KiBHistoryRawDownload
1import { Link, Navigate, useLocation } from "@tanstack/solid-router";
2import { type ParentProps, Show } from "solid-js";
3import type { Role } from "@/api/client";
4import { PageLoadError } from "@/components/layout/page-load-error";
5import { IconHome, IconLock } from "@/components/ui/icons";
6import { PageSpinner } from "@/components/ui/page-spinner";
7import { hasExactRole, hasMinRole, roleInRange } from "@/lib/roles";
8import { useAuth } from "@/stores/auth-context";
9import { useT } from "@/stores/preferences-context";
10
11// Pages kept for one audience that staff reach by URL or an old link: where
12// the school-wide view of the same data exists, point there instead.
13const STAFF_ALTERNATIVES: Record<string, { to: string; minRole: Role }> = {
14 "/marks": { to: "/management/student-marks", minRole: "teacher" },
15 "/pomodoro": { to: "/management/pomodoros", minRole: "teacher" },
16 "/students": { to: "/management/students", minRole: "manager" },
17 "/students/attendance": { to: "/management/student-attendance", minRole: "teacher" },
18 "/students/exams": { to: "/management/student-marks", minRole: "teacher" },
19};
20
21function AccessDeniedCard(props: { exactRole?: Role; userRole: Role }) {
22 const t = useT();
23 const location = useLocation();
24 // Asking "the administrator" for access reads wrong to staff — often they
25 // are the administrator. For a page kept for students or parents, say so.
26 const audience = () =>
27 props.exactRole && props.exactRole !== props.userRole && hasMinRole(props.userRole, "teacher")
28 ? props.exactRole
29 : null;
30 const alternative = () => {
31 if (!audience()) return null;
32 const alt = STAFF_ALTERNATIVES[location().pathname.replace(/\/+$/, "")];
33 return alt && hasMinRole(props.userRole, alt.minRole) ? alt.to : null;
34 };
35 return (
36 <div class="flex min-h-[50vh] items-center justify-center px-4 py-16">
37 <div class="w-full max-w-[420px] space-y-5 rounded-xl border border-border-line bg-surface-base p-8 text-center shadow-[0_10px_24px_-4px_rgba(0,0,0,0.10)]">
38 <div class="mx-auto flex h-14 w-14 items-center justify-center rounded-full bg-warning/10 text-warning-text">
39 <IconLock class="h-6 w-6" />
40 </div>
41 <Show
42 when={audience()}
43 fallback={
44 <div class="space-y-2">
45 <p class="text-4xl font-semibold tracking-tight text-text-strong">403</p>
46 <p class="text-base font-semibold text-text-strong">{t("common.accessDenied")}</p>
47 <p class="text-sm leading-[21px] text-text-subtle">{t("errors.accessDeniedDescription")}</p>
48 </div>
49 }
50 >
51 {(role) => (
52 <div class="space-y-2">
53 <p class="text-base font-semibold text-text-strong">
54 {t(role() === "parent" ? "errors.parentOnlyTitle" : "errors.studentOnlyTitle")}
55 </p>
56 <p class="text-sm leading-[21px] text-text-subtle">
57 {t(alternative() ? "errors.audienceOnlyWithAlternative" : "errors.audienceOnlyDescription")}
58 </p>
59 </div>
60 )}
61 </Show>
62 <div class="flex flex-wrap items-center justify-center gap-2">
63 <Show when={alternative()}>
64 {(to) => (
65 <Link
66 to={to()}
67 class="inline-flex h-9 items-center justify-center whitespace-nowrap rounded-lg bg-primary px-3 py-2 text-sm font-medium text-primary-foreground transition-colors hover:bg-primary/90"
68 >
69 {t("errors.openStaffView")}
70 </Link>
71 )}
72 </Show>
73 <Link
74 to="/"
75 class={
76 alternative()
77 ? "inline-flex h-9 items-center justify-center gap-1.5 whitespace-nowrap rounded-lg border border-input bg-background px-3 py-2 text-sm font-medium transition-colors hover:bg-accent"
78 : "inline-flex h-9 items-center justify-center gap-1.5 whitespace-nowrap rounded-lg bg-primary px-3 py-2 text-sm font-medium text-primary-foreground transition-colors hover:bg-primary/90"
79 }
80 >
81 <IconHome class="mr-1 h-4 w-4" />
82 {t("common.goHome")}
83 </Link>
84 </div>
85 </div>
86 </div>
87 );
88}
89
90export function RouteGuard(
91 props: ParentProps<{
92 minRole?: Role;
93 /** Inclusive upper bound (e.g. maxRole: "manager" excludes admin). */
94 maxRole?: Role;
95 /** When set, only this exact role may enter (e.g. student-only pages). */
96 exactRole?: Role;
97 }>,
98) {
99 const auth = useAuth();
100
101 const allowed = (role: Role) => {
102 if (props.exactRole) return hasExactRole(role, props.exactRole);
103 if (props.minRole || props.maxRole) return roleInRange(role, props.minRole, props.maxRole);
104 return true;
105 };
106
107 return (
108 <Show when={!auth.loading()} fallback={<PageSpinner />}>
109 {/* A failed session read (often a rate limit) gets the same full-page
110 state as a failed page: the cause, a retry that waits out the
111 limit, and the details — not a bare red box. */}
112 <Show when={!auth.error()} fallback={<PageLoadError error={auth.error()} reset={() => void auth.refresh()} />}>
113 <Show when={auth.user()} fallback={<Navigate to="/login" />}>
114 {(u) => (
115 <Show when={allowed(u().role)} fallback={<AccessDeniedCard exactRole={props.exactRole} userRole={u().role} />}>
116 {props.children}
117 </Show>
118 )}
119 </Show>
120 </Show>
121 </Show>
122 );
123}