Compare commits

..

4 commits

Author SHA1 Message Date
6ea6f2678a
* server now return hash to client
* show the link to copy for download
2022-10-28 01:06:15 +02:00
5b57ab7e2e
change forge source 2022-10-28 01:04:58 +02:00
421e72d3a3
prepare download endpoint 2022-10-28 01:04:49 +02:00
63394435a5
change fn name 2022-10-28 01:04:32 +02:00
8 changed files with 73 additions and 24 deletions

View file

@ -4,11 +4,13 @@ from werkzeug.wrappers.response import Response
from config import init from config import init
from routes.api.download import router as api_download from routes.api.download import router as api_download
from routes.api.upload import router as api_upload from routes.api.upload import router as api_upload
from routes.file import router as download
from routes.index import router as index from routes.index import router as index
app = Flask(__name__, static_url_path="/", static_folder="public") app = Flask(__name__, static_url_path="/", static_folder="public")
app.register_blueprint(index, url_prefix="/index") app.register_blueprint(index, url_prefix="/index")
app.register_blueprint(api_upload, url_prefix="/api/upload") app.register_blueprint(api_upload, url_prefix="/api/upload")
app.register_blueprint(download, url_prefix="/file")
app.register_blueprint(api_download, url_prefix="/api/download") app.register_blueprint(api_download, url_prefix="/api/download")
init() init()

View file

@ -64,20 +64,56 @@ const update = (element, text, tag = undefined) => {
*/ */
const send = (file, element) => { const send = (file, element) => {
file.text().then((content) => { file.text().then((content) => {
const req = new XMLHttpRequest();
element = update(element, "Génération des clefs...", "H3"); element = update(element, "Génération des clefs...", "H3");
gen_RSA_keypair(1024).then(([, sec_key]) => { gen_RSA_keypair(1024).then(([pub_key, sec_key]) => {
element = update(element, "Chiffrement du fichier...", "H3"); element = update(element, "Chiffrement du fichier...", "H3");
let data = { let data = {
file: RSA_enc(content, sec_key).map((v) => v.toString()), file: RSA_enc(content, sec_key).map((v) => v.toString()),
}; };
update(element, "Téléversement...", "H3"); element = update(element, "Téléversement...", "H3");
const req = new XMLHttpRequest();
req.open("POST", "api/upload"); req.open("POST", "api/upload");
req.setRequestHeader("Content-Type", "application/json"); req.setRequestHeader("Content-Type", "application/json");
req.send(JSON.stringify(data)); req.send(JSON.stringify(data));
req.onload = () => {
if (req.status == 200) {
/* Change here the area with the copy link */
let url = window.location.href.split("/");
url.pop();
url.push("file");
let main_div = element.parentElement.parentElement;
main_div.textContent = "";
let div = document.createElement("DIV");
div.textContent = "Fichier prêt !";
div.className = "link-area";
main_div.appendChild(div);
let message = document.createElement("P");
message.innerHTML = `Copiez le lien pour télécharger <code>${file.name}</code>`;
div.appendChild(message);
let input = document.createElement("INPUT");
input.value = `${url.join("/")}/${req.responseText.slice(
1,
-2
)}/${pub_key[0]}:${pub_key[1]}`;
input.readOnly = true;
div.appendChild(input);
// TODO: Change button textContent on click
let button = document.createElement("BUTTON");
button.textContent = "Copier le lien";
div.appendChild(button);
} else {
console.error("Upload failed.");
}
};
/* Here we need to store the public key and then wait for a response /* Here we need to store the public key and then wait for a response
* from the server. When the server send us a hash of the file * from the server. When the server send us a hash of the file
* we redirect the user the a wait page so the uploader can copy * we redirect the user the a wait page so the uploader can copy

View file

@ -70,7 +70,8 @@ main {
padding-top: 0.5em; padding-top: 0.5em;
} }
.upload-area { .upload-area,
.link-area {
border: 2px dashed var(--border); border: 2px dashed var(--border);
height: 70vh; height: 70vh;
width: 65vw; width: 65vw;

View file

@ -4,8 +4,9 @@ from werkzeug.wrappers.response import Response
router = Blueprint("download", __name__) router = Blueprint("download", __name__)
@router.route("", methods=["POST"]) @router.route("<file_hash>", methods=["POST"])
def download() -> Response: def download(file_hash: str) -> Response:
"""Download interface""" """Download interface"""
# TODO: Send the encrypted file to the javascript client # TODO: Send the encrypted file to the javascript client
print("download of file", file_hash)
return redirect("index") return redirect("index")

View file

@ -1,8 +1,8 @@
from time import time from time import time
from config import Config from config import Config
from flask import Blueprint, redirect, request from flask import Blueprint, redirect, request, jsonify
from utils.misc import h from utils.misc import hash_data
from werkzeug.wrappers.response import Response from werkzeug.wrappers.response import Response
router = Blueprint("upload", __name__) router = Blueprint("upload", __name__)
@ -11,14 +11,16 @@ router = Blueprint("upload", __name__)
@router.route("", methods=["POST"]) @router.route("", methods=["POST"])
def upload() -> Response: def upload() -> Response:
"""Upload interface (receive file from javascript client)""" """Upload interface (receive file from javascript client)"""
if request.method == "POST":
json = request.get_json() json = request.get_json()
if json: if json:
data = "".join(json["file"]) data = "".join(json["file"])
data_hash = h(data) data_hash = hash_data(data)
with open(f"{Config.uploads_dir}/{data_hash}", 'w') as f: with open(f"{Config.uploads_dir}/{data_hash}", 'w') as f:
f.write(data) f.write(data)
Config.database.add_file(data_hash, int(time())) Config.database.add_file(data_hash, int(time()))
# Send the hash to the javascript client
return jsonify(data_hash)
return redirect("/index") return redirect("/index")

13
src/routes/file.py Normal file
View file

@ -0,0 +1,13 @@
from config import Config
from flask import Blueprint, render_template
router = Blueprint("file", __name__)
@router.route("<int:file_hash>/<string:key_data>")
def file(file_hash: int, key_data: str) -> str:
"""Download page"""
print(f"hash : {file_hash}")
key = key_data.split(":")
print(f"key : {key}")
return render_template("index.html", config=Config, download=True)

View file

@ -29,13 +29,7 @@
<p>NPNO</p> <p>NPNO</p>
</footer> </footer>
<script <script src="https://unpkg.com/node-forge@1.0.0/dist/forge.min.js"></script>
src="https://cdnjs.cloudflare.com/ajax/libs/forge/1.3.1/forge.min.js"
integrity="sha512-95iy0RZIbw3H/FgfAj2wnCQJlzFQ+eaSfUeV/l8WVyGHKSRMzm3M/O+85j9ba/HFphkijrCTDjcuDX0BL2lthA=="
crossorigin="anonymous"
referrerpolicy="no-referrer"
></script>
<script type="module" src="../js/main.js"></script> <script type="module" src="../js/main.js"></script>
</body> </body>
</html> </html>

View file

@ -21,7 +21,7 @@ def int_to_bytes(data: int) -> bytes:
return data.to_bytes((data.bit_length() + 7) // 8, BYTEORDER) return data.to_bytes((data.bit_length() + 7) // 8, BYTEORDER)
def h(string: str) -> str: def hash_data(string: str) -> str:
"""Hash a string""" """Hash a string"""
# https://docs.python.org/3/library/sys.html#sys.set_int_max_str_digits # https://docs.python.org/3/library/sys.html#sys.set_int_max_str_digits
set_int_max_str_digits(len(string)) set_int_max_str_digits(len(string))