Home

/share-secret-with-server-web-app-python-fastapi

from datetime import datetime, timezone
from pathlib import Path
from uuid import uuid4

from fastapi import FastAPI, Form
from fastapi.responses import HTMLResponse

app = FastAPI()

STORAGE_DIR = Path("storage")
STORAGE_DIR.mkdir(exist_ok=True)


@app.get("/", response_class=HTMLResponse)
async def form():
    return """
    <!DOCTYPE html>
    <html>
    <head>
        <title>Secure Value Storage</title>
        <style>
            body {
                font-family: Arial, sans-serif;
                max-width: 500px;
                margin: 50px auto;
            }
            input {
                width: 100%;
                padding: 10px;
                margin-bottom: 10px;
                box-sizing: border-box;
            }
            button {
                padding: 10px 20px;
            }
        </style>
    </head>
    <body>
        <h2>Store Sensitive Value</h2>

        <form method="post" action="/submit">
            <input
                type="password"
                name="secret"
                placeholder="Enter sensitive value"
                required
            />
            <button type="submit">Submit</button>
        </form>
    </body>
    </html>
    """


@app.post("/submit", response_class=HTMLResponse)
async def submit(secret: str = Form(...)):
    timestamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%S%fZ")
    file_uuid = uuid4()

    filename = f"{timestamp}_{file_uuid}.txt"
    filepath = STORAGE_DIR / filename

    filepath.write_text(secret, encoding="utf-8")

    return f"""
    <html>
    <body>
        <h3>Value stored successfully</h3>
        <p>File: {filename}</p>
        <a href="/">Back</a>
    </body>
    </html>
    """


if __name__ == "__main__":
    import uvicorn

    uvicorn.run(app, host="0.0.0.0", port=8000)