diaREact/resources/js/components/pages/Form.tsx

86 lines
2.8 KiB
TypeScript
Raw Normal View History

2022-02-11 17:26:15 +01:00
import * as React from 'react';
import {EncryptStorage} from 'storage-encryption';
import {Button, Stack, TextField} from "@mui/material";
import MDEditor from '@uiw/react-md-editor';
let encryptStorage = new EncryptStorage('test'); // TODO la clef doit venir de l'utilisateur
export default function PageForm({setListPages, csrf, url, passphrase}) {
const isPassphraseSet = passphrase !== null;
const [content, setContent] = React.useState("");
2022-02-11 17:26:15 +01:00
const onSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
encryptStorage = new EncryptStorage(passphrase);
const HTMLForm : HTMLFormElement = event.currentTarget;
const decryptedFormData = new FormData(HTMLForm);
const encryptedFormData = new FormData();
for (const [key, value] of decryptedFormData.entries()) {
2022-02-11 17:26:15 +01:00
encryptStorage.encrypt('uuid'+key, value);
const newEncryptedString = localStorage.getItem('uuid'+key);
2022-02-11 17:26:15 +01:00
if (newEncryptedString) {
encryptedFormData.append(key, newEncryptedString);
}
}
encryptStorage.encrypt('uuidtext', content);
encryptedFormData.append("text", ""+localStorage.getItem('uuidtext'))
2022-02-11 17:26:15 +01:00
encryptedFormData.append('_token', csrf);
const response = await fetch(url, {
2022-02-11 17:26:15 +01:00
method: 'POST',
body: encryptedFormData
});
const json = await response.json();
const uuid = json.uuid;
for (const key of decryptedFormData.keys()) {
const newEncryptedString = localStorage.getItem('uuid'+key);
2022-02-11 17:26:15 +01:00
localStorage.setItem(uuid+key, ""+newEncryptedString);
localStorage.removeItem("uuid"+key);
}
if (json.success) {
HTMLForm.reset();
setListPages(previousList => [
{
id: uuid,
date: json.date,
title: decryptedFormData.get("title"),
content: decryptedFormData.get("text"),
},
...previousList
]);
2022-02-11 17:26:15 +01:00
}
}
if (isPassphraseSet) {
return (
<form action={url} id="postPage" method="post" onSubmit={onSubmit}>
<Stack
component="div"
2022-02-11 17:26:15 +01:00
spacing={2}
>
<TextField
label="Titre"
id="title"
name="title"
variant="outlined"
size="small"
/>
<MDEditor
value={content}
onChange={setContent}
/>
<Button variant="contained" type={"submit"}>
2022-02-11 17:26:15 +01:00
Enregistrer
</Button>
</Stack>
</form>
2022-02-11 17:26:15 +01:00
);
}
return (<div></div>);
}