77 lines
2.0 KiB
TypeScript
77 lines
2.0 KiB
TypeScript
import { Signal, useSignal, useSignalEffect } from "@preact/signals";
|
|
|
|
import KeysCreate from "@/islands/KeysCreate.tsx";
|
|
import KeysUnlock from "@/islands/KeysUnlock.tsx";
|
|
import { post_json } from "@/src/client.ts";
|
|
import { load_master_key } from "@/src/key_store.ts";
|
|
import { type GetKeyResponse, verify_key_check } from "@/src/keys.ts";
|
|
|
|
interface KeysNewProps {
|
|
page: Signal<string>;
|
|
}
|
|
|
|
export default function KeysNew(props: KeysNewProps) {
|
|
const step = useSignal<"loading" | "create" | "unlock">("loading");
|
|
const account = useSignal<GetKeyResponse | null>(null);
|
|
const load_error = useSignal("");
|
|
const unlock_message = useSignal("");
|
|
|
|
async function load_account() {
|
|
step.value = "loading";
|
|
const code = localStorage.getItem("code");
|
|
if (!code) {
|
|
props.page.value = "askcode";
|
|
return;
|
|
}
|
|
|
|
const result = await post_json<GetKeyResponse>("/api/get_key", { code });
|
|
if (!result.ok) {
|
|
load_error.value = result.error;
|
|
return;
|
|
}
|
|
|
|
account.value = result.data;
|
|
const key_check = result.data.key_check;
|
|
if (!key_check) {
|
|
step.value = "create";
|
|
return;
|
|
}
|
|
|
|
const local_key = await load_master_key(result.data.user_id).catch(() => undefined);
|
|
if (local_key && await verify_key_check(local_key, key_check)) {
|
|
props.page.value = "hub";
|
|
} else {
|
|
step.value = "unlock";
|
|
}
|
|
}
|
|
|
|
useSignalEffect(() => {
|
|
load_account();
|
|
});
|
|
|
|
function go_to_hub() {
|
|
props.page.value = "hub";
|
|
}
|
|
|
|
if (step.value === "loading" || !account.value) {
|
|
return load_error.value
|
|
? <p role="alert" class="text-center text-error-600 dark:text-error-400">{load_error.value}</p>
|
|
: <p class="text-center text-gray-800 dark:text-gray-400">Loading...</p>;
|
|
}
|
|
|
|
if (step.value === "create") {
|
|
return (
|
|
<KeysCreate
|
|
user_id={account.value.user_id}
|
|
on_done={go_to_hub}
|
|
on_needs_unlock={(message) => {
|
|
unlock_message.value = message;
|
|
load_account();
|
|
}}
|
|
/>
|
|
);
|
|
}
|
|
|
|
return <KeysUnlock account={account.value} message={unlock_message.value} on_done={go_to_hub} />;
|
|
}
|