File size: 1,867 Bytes
33962ff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"use client";
import { useState } from "react";
export function AccessToken({ admin = false }: { admin?: boolean }) {
  const [token, setToken] = useState(""),
    [message, setMessage] = useState("");
  async function save() {
    sessionStorage.setItem(admin ? "vm-admin-token" : "vm-user-token", token);
    if (!admin) {
      try {
        const r = await fetch("/api/access", {
          method: "POST",
          headers: { Authorization: `Bearer ${token}` },
        });
        if (!r.ok) throw new Error("Access denied");
        window.location.reload();
      } catch (e) {
        sessionStorage.removeItem("vm-user-token");
        setMessage(String(e));
      }
    } else setMessage("Administrator token saved for this tab");
  }
  return (
    <div className="my-3 flex flex-wrap items-center gap-2 text-sm">
      <label>
        {admin ? "Admin" : "Session"} access token{" "}
        <input
          aria-label={admin ? "Admin token" : "Session token"}
          type="password"
          autoComplete="off"
          className="rounded-lg border border-line bg-surface px-3 py-2"
          value={token}
          onChange={(e) => setToken(e.target.value)}
        />
      </label>
      <button
        className="rounded-lg border border-line px-3 py-2 hover:bg-surface-2"
        onClick={() => void save()}
      >
        Connect {admin ? "administrator" : "private library"}
      </button>
      <button
        className="text-muted"
        onClick={() => {
          sessionStorage.removeItem(admin ? "vm-admin-token" : "vm-user-token");
          if (!admin)
            void fetch("/api/access", { method: "DELETE" }).then(() =>
              window.location.reload(),
            );
          setMessage("Cleared");
        }}
      >
        Disconnect
      </button>
      <span role="status">{message}</span>
    </div>
  );
}