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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212import { useGlobalStore } from "#src/utils";
import { useEffect } from "react";
import { Link, Outlet, useLocation, useNavigate } from "react-router-dom";
import { Loader, GlobalErrorHandler } from ".";
import * as Auth from "aws-amplify/auth";
import { usePostHog } from "posthog-js/react";
import { useUser } from "../queries";
import * as Avatar from "@radix-ui/react-avatar";
import generateAbbreviation from "#src/utils/generateAbbreviation.ts";
import * as DropdownMenu from "@radix-ui/react-dropdown-menu";
import { useMsalTokenRefresh } from "../hooks";
import styles from "./Navigation.module.scss";
import { Logo } from "./Logo";
import * as AccessibleIcon from "@radix-ui/react-accessible-icon";
import { MdDarkMode, MdOutlineDarkMode } from "react-icons/md";
import { Footer } from "./Footer";
export const Navigation = () => {
const location = useLocation();
const navigate = useNavigate();
const { loading, authenticated, setAuthenticated, darkMode, setDarkMode } =
useGlobalStore();
const posthog = usePostHog();
const { data: user } = useUser();
// Handle MSAL token refresh
useMsalTokenRefresh();
useEffect(() => {
window.scrollTo(0, 0);
}, [location]);
useEffect(() => {
if (darkMode) {
document.body.classList.add("dark");
} else {
document.body.classList.remove("dark");
}
}, [darkMode]);
useEffect(() => {
const checkAuth = async () => {
// Check for SSO session first
const ssoToken = localStorage.getItem("sso_token");
if (ssoToken) {
// Parse the JWT to get the OID
try {
const payload = JSON.parse(atob(ssoToken.split(".")[1]));
const userId = payload.oid || payload.sub;
// Validate with backend before trusting the token
if (userId) {
try {
const API = await import("aws-amplify/api");
await API.get({
apiName: "auth",
path: "/getAccount",
}).response;
// Only set authenticated if backend validation succeeds
setAuthenticated(userId);
posthog?.identify(userId, { email: payload?.email });
} catch (backendError: any) {
// Backend rejected - token is invalid or user not authorized
console.error(
"Backend validation failed on page load:",
backendError
);
localStorage.removeItem("sso_token");
setAuthenticated(false);
// Parse error message from response - AWS Amplify wraps errors differently
let errorMessage = "You are not authorized to access Equalify.";
// Check direct message property
if (backendError?.message) {
errorMessage = backendError.message;
}
// Check response body
else if (backendError?.response?.body) {
try {
const errorBody = backendError.response.body;
const parsed =
typeof errorBody === "string"
? JSON.parse(errorBody)
: errorBody;
errorMessage = parsed?.message || errorMessage;
} catch (e) {
// Keep default error message
}
}
// public pages
if (
!location.pathname.startsWith("/login") &&
!location.pathname.startsWith("/shared/")
) {
navigate("/login?error=" + encodeURIComponent(errorMessage));
}
return;
}
}
} catch (error) {
console.error("Failed to parse SSO token:", error);
localStorage.removeItem("sso_token");
setAuthenticated(false);
}
if (location.pathname === "/") {
navigate("/audits");
}
return;
}
// Check Cognito session
const attributes = (await Auth.fetchAuthSession()).tokens?.idToken
?.payload;
if (!attributes) {
setAuthenticated(false);
if (!location.pathname.startsWith("/shared/")) {
navigate(`/${location.search}`);
}
} else {
setAuthenticated(attributes?.sub as unknown as boolean);
posthog?.identify(attributes?.sub, { email: attributes?.email });
if (location.pathname === "/") {
navigate("/audits");
}
}
};
checkAuth();
}, []);
// on location change, focus to the first element with class 'initial-focus-element'
useEffect(() => {
const focusEl = document.getElementsByClassName(
"initial-focus-element"
)[0] as HTMLElement;
const tabIndex = focusEl?.getAttribute("tabindex");
focusEl?.setAttribute("tabindex", tabIndex ?? "-1");
focusEl?.focus();
}, [location]);
const isAuthRoute =
location.pathname.startsWith("/login") ||
location.pathname.startsWith("/signup");
const navItems = !authenticated
? [
{ label: "Log In", value: "/login" },
{ label: "Sign Up", value: "/signup" },
]
: [
{ label: "Audits", value: "/audits" },
{ label: "Logs", value: "/logs" },
{ label: "Account", value: "/account" },
];
return (
<>
<div className="app-container" data-vaul-drawer-wrapper>
<GlobalErrorHandler />
{!isAuthRoute && (
<div className={styles.navigation}>
<div className={styles.content}>
<Logo />
<div className={styles.nav_menu}>
{navItems.map((obj) => (
<Link
key={obj.value}
to={obj.value}
className={
styles["link"] +
" " +
(location.pathname === obj.value ? styles["active"] : "")
}
>
{obj.label}
</Link>
))}
</div>
<div className={styles.nav_buttons}>
{authenticated && user && (
<div className={styles["user_info"]}>
Signed in as <b>{user.name}</b>
<br />
<Link className={styles["logout"]} to="/logout">Logout</Link>
</div>
)}
{/* <button onClick={() => setDarkMode(!darkMode)}>
<AccessibleIcon.Root
label={`Switch to ${darkMode ? "Light Mode" : "Dark Mode"}`}
>
{!darkMode ? <MdOutlineDarkMode /> : <MdDarkMode />}
</AccessibleIcon.Root>
</button> */}
</div>
</div>
</div>
)}
<div className="container page-content">
{loading && <Loader />}
<Outlet />
</div>
<Footer />
</div>
</>
);
};