Last active
May 31, 2024 17:28
-
-
Save KokoseiJ/053f09098e39d1b2fe8befcc47df6218 to your computer and use it in GitHub Desktop.
Cat Tab CDN server implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import pam | |
from hashlib import sha256 | |
from fastapi import FastAPI, Request, File, Depends, HTTPException | |
from fastapi.staticfiles import StaticFiles | |
from fastapi.security import HTTPBasic, HTTPBasicCredentials | |
from pydantic import BaseModel | |
from typing import Annotated | |
CAT_FOLDER = os.environ.get("CAT_FOLDER", "./cats") | |
AUTHORIZED_USERS = os.environ.get( | |
"CAT_ADMIN", "kokoseij,chick0,hurrhnn" | |
).split(",") | |
app = FastAPI() | |
security = HTTPBasic() | |
p = pam.pam() | |
app.mount("/cats", StaticFiles(directory=CAT_FOLDER)) | |
class CatEntry(BaseModel): | |
hash: str | |
url: str | |
@app.post("/upload") | |
def cat_upload( | |
file: Annotated[bytes, File()], | |
cred: Annotated[HTTPBasicCredentials, Depends(security)] | |
): | |
if not p.authenticate(cred.username, cred.password): | |
raise HTTPException(status_code=401, detail=">:(") | |
hashed = sha256(file).hexdigest() | |
newpath = os.path.join(CAT_FOLDER, f"{hashed}.webp") | |
with open(newpath, "wb") as f: | |
f.write(file) | |
return newpath | |
@app.get("/list.json") | |
def cat_list(request: Request) -> list[CatEntry]: | |
return [ | |
CatEntry( | |
hash=filename.rstrip(".webp"), | |
url=f"{str(request.base_url).rstrip("/")}/cats/{filename}" | |
) | |
for filename in os.listdir(CAT_FOLDER) | |
if filename.endswith(".webp") | |
] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[Unit] | |
Description="Cat Tab CDN" | |
Wants=nginx.service | |
After=nginx.service | |
After=network.target | |
[Service] | |
User=nginx | |
Group=nginx | |
WorkingDirectory=/mnt/share/service/cat-tab | |
RuntimeDirectory=cattab | |
RuntimeDirectoryMode=775 | |
ExecStart=/mnt/share/service/cat-tab/venv/bin/uvicorn --forwarded-allow-ips "*" --uds /run/cattab/cattab.sock 'car_server:app' | |
[Install] | |
WantedBy=multi-user.target |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment