summaryrefslogtreecommitdiff
path: root/front/src/routes/keys.jsx
blob: 5b50fa9b5ace465efda5b631fa05328dd8be50c6 (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
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
import Modal from "react-modal";
import { useEffect, useState, useCallback } from "react";
import { useAuthContext } from "../context/auth_context";

Modal.setAppElement("#root");

const MINIMIZE_KEY_LEN = 40;
const minimizeKey = (key) => {
  const n = key.length;
  if (n >= MINIMIZE_KEY_LEN) {
    const half = Math.floor(MINIMIZE_KEY_LEN / 2);
    return key.substring(0, half) + "..." + key.substring(n - half, n);
  }
  return key;
};

const KeyCard = ({ onDelete, props }) => {
  const { id, name, key } = props;

  const deleteThisKey = () => {
    if (
      window.confirm(
        "Are you sure? This will close all your currently opened ssh sessions."
      )
    ) {
      fetch(`/api/keys/${id}`, {
        credentials: "same-origin",
        method: "DELETE",
      })
        .then((r) => r.json())
        .then((d) => d.success && onDelete && onDelete());
    }
  };

  return (
    <div className="key-card">
      <h4 style={{ flex: 1 }}>{name}</h4>
      <p style={{ flex: 4 }}>{minimizeKey(key)}</p>

      <button
        style={{ flex: 0 }}
        className="button red"
        onClick={deleteThisKey}
      >
        Delete
      </button>
    </div>
  );
};

const AddKeyButton = ({ onSave }) => {
  const [open, setOpen] = useState(false);
  const [name, setName] = useState("");
  const [key, setKey] = useState("");
  const [errors, setErrors] = useState(null);

  const setDefaults = () => {
    setName("");
    setKey("");
    setErrors(null);
  };

  const close = () => {
    setDefaults();
    setOpen(false);
  };

  const createKey = () => {
    fetch(`/api/player/keys`, {
      credentials: "same-origin",
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        key: key.trim(),
        name: name.trim(),
      }),
    })
      .then((r) => r.json())
      .then((d) => {
        if (d.success) {
          if (onSave) {
            onSave();
          }
          close();
        } else if (d.errors) {
          if (typeof d.errors === "object") {
            setErrors(
              Object.keys(d.errors).map(
                (field) => `${field}: ${d.errors[field].join(",")}`
              )
            );
          } else {
            setErrors([d.errors]);
          }
        }
      });
  };

  return (
    <div>
      <button className="button" onClick={() => setOpen(true)}>
        + Add Key
      </button>
      <Modal
        isOpen={open}
        onRequestClose={close}
        className="modal"
        contentLabel="Add Key"
      >
        <div>
          <h3>Add SSH Key</h3>
          <p>
            Not sure about this? Check{" "}
            <a
              href="https://www.ssh.com/academy/ssh/keygen"
              target="_blank"
              rel="noreferrer"
            >
              here
            </a>{" "}
            for help!
          </p>
          <hr />
          <p>Key Name *</p>
          <input
            value={name}
            onChange={(e) => setName(e.target.value)}
            required
          />
        </div>
        <div>
          <p>SSH Key *</p>
          <textarea
            cols={40}
            rows={5}
            value={key}
            onChange={(e) => setKey(e.target.value)}
            required
          />
        </div>
        <div>
          {errors && (
            <div style={{ color: "red" }}>
              {errors.map((error, i) => (
                <p key={i}>{error}</p>
              ))}
            </div>
          )}
        </div>
        <div className="flex-end-row">
          <button className="button" onClick={createKey}>
            Add
          </button>
          <button className="button red" onClick={close}>
            Cancel
          </button>
        </div>
      </Modal>
    </div>
  );
};

export const Keys = () => {
  const {
    player: { id: userId },
  } = useAuthContext();
  const [keys, setKeys] = useState(null);

  const refreshKeys = useCallback(
    () =>
      fetch(`/api/player/${userId}/keys`)
        .then((r) => r.json())
        .then((keys) => setKeys(keys)),
    [userId]
  );

  useEffect(() => {
    if (userId) {
      refreshKeys();
    }
  }, [userId, refreshKeys]);

  if (!keys) return <p>Loading...</p>;

  if (Array.isArray(keys)) {
    return (
      <>
        <h2>My Keys</h2>
        <AddKeyButton onSave={refreshKeys} />
        <div className="key-card-collection">
          {keys.length ? (
            keys.map((key) => (
              <KeyCard key={key.id} onDelete={refreshKeys} props={key} />
            ))
          ) : (
            <p>Looks like you've got no keys, try adding some!</p>
          )}
        </div>
      </>
    );
  }
};