add import export

This commit is contained in:
Sasha 2023-10-27 16:46:24 +02:00
parent 4183b2b13f
commit 1e8b2af982
No known key found for this signature in database
2 changed files with 61 additions and 5 deletions

View File

@ -2,7 +2,7 @@ import React from "react";
import { Block, BlockTypes } from "@/components/Block";
import { Button } from "@/components/Button";
import { Subtitle } from "@/components/Subtitle";
import { useStore, useWallet } from "@/hooks";
import { useRLN, useStore, useWallet } from "@/hooks";
import { useKeystore } from "@/hooks/useKeystore";
export const Keystore: React.FunctionComponent<{}> = () => {
@ -12,6 +12,8 @@ export const Keystore: React.FunctionComponent<{}> = () => {
const { password, onPasswordChanged } = usePassword();
const { selectedKeystore, onKeystoreChanged } = useSelectedKeystore();
const { onExportKeystore, onImportKeystoreFileChange } =
useImportExportKeystore();
const credentialsNodes = React.useMemo(
() =>
@ -28,8 +30,20 @@ export const Keystore: React.FunctionComponent<{}> = () => {
<Block type={BlockTypes.FlexHorizontal}>
<Subtitle>Keystore</Subtitle>
<div>
<Button>Import</Button>
<Button className="ml-2">Export</Button>
<Button>
<label htmlFor="keystore-import" className="cursor-pointer">
Import
</label>
</Button>
<input
id="keystore-import"
type="file"
className="hidden"
onChange={onImportKeystoreFileChange}
/>
<Button className="ml-2" onClick={onExportKeystore}>
Export
</Button>
</div>
</Block>
@ -105,3 +119,40 @@ function useSelectedKeystore() {
onKeystoreChanged,
};
}
function useImportExportKeystore() {
const { rln } = useRLN();
const onExportKeystore = () => {
if (!rln) {
return;
}
const filename = "keystore.json";
const text = rln.keystore.toString();
const file = new File([text], filename, {
type: "application/json",
});
const link = document.createElement("a");
link.href = URL.createObjectURL(file);
link.download = filename;
link.click();
};
const onImportKeystoreFileChange = async (
event: React.FormEvent<HTMLInputElement>
) => {
const file = event.currentTarget?.files?.[0];
if (!file || !rln) {
return;
}
const text = await file.text();
rln.importKeystore(text);
};
return {
onExportKeystore,
onImportKeystoreFileChange,
};
}

View File

@ -42,7 +42,7 @@ export class RLN implements IRLN {
public rlnInstance: undefined | RLNInstance;
public rlnContract: undefined | RLNContract;
public readonly keystore: Keystore;
public keystore: Keystore;
private initialized = false;
private initializing = false;
@ -135,9 +135,14 @@ export class RLN implements IRLN {
}
public async saveKeystore() {
localStorage.setItem("keystore", this.keystore.toString());
// localStorage.setItem("keystore", this.keystore.toString());
this.emitKeystoreKeys();
}
public importKeystore(value: string) {
this.keystore = Keystore.fromString(value) || Keystore.create();
this.saveKeystore();
}
}
export const rln = typeof window === "undefined" ? undefined : new RLN();