-
-
Notifications
You must be signed in to change notification settings - Fork 123
/
Copy pathauth.ts
27 lines (24 loc) · 814 Bytes
/
auth.ts
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
export default defineNuxtRouteMiddleware(async () => {
const ctx = useAuthContext();
const api = useUserApi();
const redirectTo = useState("authRedirect");
if (!ctx.isAuthorized()) {
if (window.location.pathname !== "/") {
console.debug("[middleware/auth] isAuthorized returned false, redirecting to /");
redirectTo.value = window.location.pathname;
return navigateTo("/");
}
}
if (!ctx.user) {
console.log("Fetching user data");
const { data, error } = await api.user.self();
if (error) {
if (window.location.pathname !== "/") {
console.debug("[middleware/user] user is null and fetch failed, redirecting to /");
redirectTo.value = window.location.pathname;
return navigateTo("/");
}
}
ctx.user = data.item;
}
});