blob: eb272a6729753152db8d982a5b66fca172ed7391 (
plain)
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
|
import { useEffect, useRef, useState } from "react";
type ExchangeState = "working" | "failed" | "missing";
const MagicLink = function () {
const started = useRef(false);
const [state, setState] = useState<ExchangeState>("working");
useEffect(() => {
// React Strict Mode runs effects twice in development. Never redeem twice.
if (started.current) return;
started.current = true;
const params = new URLSearchParams(window.location.search);
const token = params.get("token");
if (!token) {
setState("missing");
return;
}
// Keep the credential out of browser history and subsequent Referer headers.
window.history.replaceState({}, "", window.location.pathname);
void fetch("/auth/magic-link/exchange", {
method: "POST",
credentials: "include",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ token: token }),
})
.then((response) => {
if (!response.ok) throw new Error("Magic-link exchange failed");
window.location.replace("/");
})
.catch(() => setState("failed"));
}, []);
if (state === "missing") {
return <p>This login link is missing its token.</p>;
}
if (state === "failed") {
return <p>This login link is invalid or has expired.</p>;
}
return <p>Signing you in…</p>;
};
export default MagicLink;
|