aboutsummaryrefslogtreecommitdiff
path: root/jb-ui/src/pages/MagicWallet.tsx
blob: 21331f93dd194abcdfbbb0102a99a83025318713 (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
47
48
49
50
51
52
53
54
55
56
57
58
import {
  WalletApi as JBApi,
  CashoutConfirmation,
  Configuration,
} from "@/api_jb";
import { useEffect, useRef, useState } from "react";

type ExchangeState = "working" | "failed" | "missing";

const MagicWallet = function () {
  const started = useRef(false);
  const [state, setState] = useState<ExchangeState>("working");
  const [errorMsg, setErrorMesg] = useState("");

  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);

    const cc = {
      token: token,
    } as CashoutConfirmation;

    const config = new Configuration({ basePath: "http://localhost:5174" });
    new JBApi(config)
      .confirmCashoutWalletCashoutConfirmPost(cc)
      .then((res) => {
        console.log("confirmCashoutWalletCashoutConfirmPost", res.data);
        // if (!res.ok) throw new Error("Magic-link exchange failed");
        window.location.replace("/");
      })
      .catch((err) => {
        const response = err?.response?.data;
        setErrorMesg(response?.detail ?? err.message);
        setState("failed");
      });
  }, []);

  if (state === "missing") {
    return <p>This login link is missing its token.</p>;
  }
  if (state === "failed") {
    return <p>{errorMsg}</p>;
  }
  return <p>Signing you in…</p>;
};

export default MagicWallet;