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 current ssh sessions."
)
) {
fetch(`/api/keys/${id}`, {
credentials: "same-origin",
method: "DELETE",
})
.then((r) => r.json())
.then((d) => d.success && onDelete && onDelete());
}
};
return (
{name}
{minimizeKey(key)}
);
};
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 (
Add SSH Key
Not sure about this? Check{" "}
here
{" "}
for help!
Key Name *
setName(e.target.value)}
required
/>
{errors && (
{errors.map((error, i) => (
{error}
))}
)}
);
};
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 Loading...
;
if (Array.isArray(keys)) {
return (
<>
My Keys
{keys.length ? (
keys.map((key) => (
))
) : (
Looks like you've got no keys, try adding some!
)}
>
);
}
};