forked from Bitcoindefi/OpenAO
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseAuthRedirect.ts
More file actions
90 lines (73 loc) · 2.66 KB
/
Copy pathuseAuthRedirect.ts
File metadata and controls
90 lines (73 loc) · 2.66 KB
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
"use client";
import { usePathname, useRouter } from "next/navigation";
import { useEffect, useState } from "react";
import type { AuthErrorResponse, AuthSession } from "../lib/auth";
type UseAuthRedirectOptions = {
redirectTo: string;
when: "authenticated" | "unauthenticated";
preserveRedirect?: boolean;
};
export function useAuthRedirect({
redirectTo,
when,
preserveRedirect = false,
}: UseAuthRedirectOptions) {
const pathname = usePathname();
const router = useRouter();
const [session, setSession] = useState<AuthSession | null>(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
let cancelled = false;
const buildRedirectTarget = () => {
if (!preserveRedirect || when !== "unauthenticated") {
return redirectTo;
}
const currentPath =
typeof window === "undefined"
? pathname
: `${pathname}${window.location.search}`;
const params = new URLSearchParams();
params.set("redirect", currentPath);
return `${redirectTo}?${params.toString()}`;
};
const getRedirectParam = () => {
if (typeof window === "undefined") {
return "";
}
return new URLSearchParams(window.location.search).get("redirect")?.trim() || "";
};
const loadSession = async () => {
try {
const response = await fetch("/api/auth/me", { cache: "no-store" });
if (!response.ok) {
if (!cancelled && when === "unauthenticated") {
router.replace(buildRedirectTarget());
}
return;
}
const result = (await response.json()) as AuthSession | AuthErrorResponse;
if (cancelled || "error" in result) {
return;
}
setSession(result);
if (when === "authenticated") {
const redirectPath = getRedirectParam();
router.replace(redirectPath || redirectTo);
}
} catch {
if (!cancelled && when === "unauthenticated") {
router.replace(buildRedirectTarget());
}
} finally {
if (!cancelled) {
setLoading(false);
}
}
};
void loadSession();
return () => {
cancelled = true;
};
}, [pathname, preserveRedirect, redirectTo, router, when]);
return { session, loading };
}