Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,287 +1,296 @@
|
|
| 1 |
-
import os
|
| 2 |
-
import shutil
|
| 3 |
-
import aiofiles
|
| 4 |
-
from fastapi import (
|
| 5 |
-
FastAPI, UploadFile, File, HTTPException, Request, Depends, Form, APIRouter, status
|
| 6 |
-
)
|
| 7 |
-
|
| 8 |
-
from fastapi.
|
| 9 |
-
from fastapi.
|
| 10 |
-
from
|
| 11 |
-
|
| 12 |
-
import
|
| 13 |
-
import
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
logger.
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
"
|
| 59 |
-
"
|
| 60 |
-
"
|
| 61 |
-
"
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
)
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 287 |
uvicorn.run("app:app", host="0.0.0.0", port=7860, reload=True)
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import shutil
|
| 3 |
+
import aiofiles
|
| 4 |
+
from fastapi import (
|
| 5 |
+
FastAPI, UploadFile, File, HTTPException, Request, Depends, Form, APIRouter, status
|
| 6 |
+
)
|
| 7 |
+
import datetime
|
| 8 |
+
from fastapi.responses import HTMLResponse, FileResponse, JSONResponse, RedirectResponse, Response
|
| 9 |
+
from fastapi.staticfiles import StaticFiles
|
| 10 |
+
from fastapi.templating import Jinja2Templates
|
| 11 |
+
from pathlib import Path
|
| 12 |
+
import logging # Standard logging
|
| 13 |
+
import datetime # For admin logic timestamps
|
| 14 |
+
import math # For admin logic format_bytes
|
| 15 |
+
from typing import List, Optional # For admin logic type hinting
|
| 16 |
+
|
| 17 |
+
# --- Configuration ---
|
| 18 |
+
BASE_DIR = Path(__file__).resolve().parent
|
| 19 |
+
FILES_DIR = BASE_DIR / "uploaded_files"
|
| 20 |
+
STATIC_DIR = BASE_DIR / "static"
|
| 21 |
+
TEMPLATES_DIR = BASE_DIR / "templates"
|
| 22 |
+
# LOG_FILE constant removed
|
| 23 |
+
|
| 24 |
+
# Create directories if they don't exist
|
| 25 |
+
FILES_DIR.mkdir(parents=True, exist_ok=True)
|
| 26 |
+
STATIC_DIR.mkdir(parents=True, exist_ok=True)
|
| 27 |
+
TEMPLATES_DIR.mkdir(parents=True, exist_ok=True)
|
| 28 |
+
|
| 29 |
+
# --- Logging Configuration (Console Only) ---
|
| 30 |
+
logger = logging.getLogger("file_app")
|
| 31 |
+
logger.setLevel(logging.INFO)
|
| 32 |
+
# No file handler, no propagate=False. Logs will go to console via root logger.
|
| 33 |
+
|
| 34 |
+
logger.info("Application starting up... Logging to console.")
|
| 35 |
+
|
| 36 |
+
app = FastAPI(title="File Uploader/Downloader")
|
| 37 |
+
|
| 38 |
+
# Setup Jinja2 templates
|
| 39 |
+
templates = Jinja2Templates(directory=str(TEMPLATES_DIR))
|
| 40 |
+
|
| 41 |
+
# --- Admin Panel Configuration & Logic ---
|
| 42 |
+
ADMIN_EMAIL = "admin@example.com"
|
| 43 |
+
ADMIN_PASSWORD = "adminpassword"
|
| 44 |
+
ADMIN_SESSION_COOKIE_NAME = "admin_session_id"
|
| 45 |
+
ADMIN_SESSION_SECRET_VALUE = "my_super_secret_admin_session_value_for_demo_only_change_me"
|
| 46 |
+
|
| 47 |
+
admin_router = APIRouter(
|
| 48 |
+
prefix="/admin",
|
| 49 |
+
tags=["Admin"],
|
| 50 |
+
)
|
| 51 |
+
|
| 52 |
+
# --- Admin Helper Functions ---
|
| 53 |
+
def get_file_info(file_path: Path):
|
| 54 |
+
try:
|
| 55 |
+
if file_path.is_file():
|
| 56 |
+
stat_info = file_path.stat()
|
| 57 |
+
return {
|
| 58 |
+
"name": file_path.name,
|
| 59 |
+
"size_bytes": stat_info.st_size,
|
| 60 |
+
"size_human": format_bytes(stat_info.st_size),
|
| 61 |
+
"modified_at": datetime.datetime.fromtimestamp(stat_info.st_mtime).strftime('%Y-%m-%d %H:%M:%S UTC'),
|
| 62 |
+
"url": f"/download/{file_path.name}"
|
| 63 |
+
}
|
| 64 |
+
except Exception as e:
|
| 65 |
+
logger.error(f"Admin: Error getting file info for {file_path}: {e}")
|
| 66 |
+
return None
|
| 67 |
+
return None
|
| 68 |
+
|
| 69 |
+
def format_bytes(bytes_val, decimals=2):
|
| 70 |
+
if bytes_val == 0: return '0 Bytes'
|
| 71 |
+
k = 1024
|
| 72 |
+
dm = decimals if decimals >= 0 else 0
|
| 73 |
+
sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB']
|
| 74 |
+
i = 0
|
| 75 |
+
if bytes_val > 0:
|
| 76 |
+
i = int(math.floor(math.log(bytes_val) / math.log(k)))
|
| 77 |
+
if i >= len(sizes): i = len(sizes) -1
|
| 78 |
+
return f"{bytes_val / (k**i):.{dm}f} {sizes[i]}"
|
| 79 |
+
|
| 80 |
+
# get_log_lines function removed as file logging is removed.
|
| 81 |
+
|
| 82 |
+
# --- Admin Authentication Dependencies ---
|
| 83 |
+
async def get_current_admin(request: Request):
|
| 84 |
+
session_cookie = request.cookies.get(ADMIN_SESSION_COOKIE_NAME)
|
| 85 |
+
if session_cookie == ADMIN_SESSION_SECRET_VALUE:
|
| 86 |
+
return {"email": ADMIN_EMAIL}
|
| 87 |
+
|
| 88 |
+
current_path = request.url.path
|
| 89 |
+
if current_path not in [app.url_path_for("admin_login_page"), app.url_path_for("admin_authenticate")]:
|
| 90 |
+
logger.info(f"Admin: Unauthorized access attempt to {current_path}, redirecting to login.")
|
| 91 |
+
return RedirectResponse(url=app.url_path_for("admin_login_page"), status_code=status.HTTP_307_TEMPORARY_REDIRECT)
|
| 92 |
+
return None
|
| 93 |
+
|
| 94 |
+
async def verify_admin_auth(request: Request):
|
| 95 |
+
admin_user = await get_current_admin(request)
|
| 96 |
+
if isinstance(admin_user, RedirectResponse):
|
| 97 |
+
raise HTTPException(
|
| 98 |
+
status_code=status.HTTP_307_TEMPORARY_REDIRECT,
|
| 99 |
+
detail="Redirecting to login.",
|
| 100 |
+
headers={"Location": app.url_path_for("admin_login_page")},
|
| 101 |
+
)
|
| 102 |
+
if not admin_user:
|
| 103 |
+
logger.warning(f"Admin: Strict auth verification failed for {request.url.path}.")
|
| 104 |
+
raise HTTPException(
|
| 105 |
+
status_code=status.HTTP_401_UNAUTHORIZED,
|
| 106 |
+
detail="Not authenticated",
|
| 107 |
+
headers={"WWW-Authenticate": "Bearer"},
|
| 108 |
+
)
|
| 109 |
+
return admin_user
|
| 110 |
+
|
| 111 |
+
# --- Admin Routes ---
|
| 112 |
+
@admin_router.get("/login", response_class=HTMLResponse, name="admin_login_page")
|
| 113 |
+
async def admin_login_page(request: Request):
|
| 114 |
+
logger.info("Admin: Login page accessed.")
|
| 115 |
+
current_year = datetime.datetime.now(datetime.timezone.utc).year # Get current UTC year
|
| 116 |
+
return templates.TemplateResponse(
|
| 117 |
+
"admin_login.html",
|
| 118 |
+
{
|
| 119 |
+
"request": request,
|
| 120 |
+
"url_for": app.url_path_for,
|
| 121 |
+
"current_year": current_year # Add current year to context
|
| 122 |
+
}
|
| 123 |
+
)
|
| 124 |
+
|
| 125 |
+
@admin_router.post("/auth", name="admin_authenticate")
|
| 126 |
+
async def admin_authenticate(request: Request, email: str = Form(...), password: str = Form(...)):
|
| 127 |
+
if email == ADMIN_EMAIL and password == ADMIN_PASSWORD:
|
| 128 |
+
logger.info(f"Admin: Successful login for email {email}.")
|
| 129 |
+
response = RedirectResponse(url=app.url_path_for("admin_dashboard"), status_code=status.HTTP_303_SEE_OTHER)
|
| 130 |
+
response.set_cookie(
|
| 131 |
+
key=ADMIN_SESSION_COOKIE_NAME, value=ADMIN_SESSION_SECRET_VALUE,
|
| 132 |
+
httponly=True, samesite="lax", max_age=30 * 60
|
| 133 |
+
)
|
| 134 |
+
return response
|
| 135 |
+
else:
|
| 136 |
+
logger.warning(f"Admin: Failed login attempt for email {email}.")
|
| 137 |
+
error_msg = "Invalid email or password."
|
| 138 |
+
return templates.TemplateResponse(
|
| 139 |
+
"admin_login.html",
|
| 140 |
+
{"request": request, "error": error_msg, "url_for": app.url_path_for},
|
| 141 |
+
status_code=status.HTTP_401_UNAUTHORIZED
|
| 142 |
+
)
|
| 143 |
+
|
| 144 |
+
@admin_router.get("/logout", name="admin_logout")
|
| 145 |
+
async def admin_logout(request: Request):
|
| 146 |
+
logger.info("Admin: Logout initiated.")
|
| 147 |
+
response = RedirectResponse(url=app.url_path_for("admin_login_page"), status_code=status.HTTP_303_SEE_OTHER)
|
| 148 |
+
response.delete_cookie(ADMIN_SESSION_COOKIE_NAME, httponly=True, samesite="lax")
|
| 149 |
+
return response
|
| 150 |
+
|
| 151 |
+
@admin_router.get("/dashboard", response_class=HTMLResponse, name="admin_dashboard")
|
| 152 |
+
async def admin_dashboard(request: Request, admin_user: dict = Depends(get_current_admin)):
|
| 153 |
+
if isinstance(admin_user, RedirectResponse): return admin_user
|
| 154 |
+
if not admin_user: return RedirectResponse(url=app.url_path_for("admin_login_page"), status_code=status.HTTP_307_TEMPORARY_REDIRECT)
|
| 155 |
+
|
| 156 |
+
logger.info(f"Admin: Dashboard accessed by {admin_user.get('email')}.")
|
| 157 |
+
num_files = 0
|
| 158 |
+
try:
|
| 159 |
+
num_files = len([name for name in os.listdir(FILES_DIR) if (FILES_DIR / name).is_file()])
|
| 160 |
+
except Exception as e:
|
| 161 |
+
logger.error(f"Admin: Error counting files for dashboard: {e}")
|
| 162 |
+
|
| 163 |
+
# log_lines_count removed
|
| 164 |
+
return templates.TemplateResponse("admin_dashboard.html", {
|
| 165 |
+
"request": request,
|
| 166 |
+
"num_files": num_files,
|
| 167 |
+
"admin_user": admin_user,
|
| 168 |
+
"url_for": app.url_path_for
|
| 169 |
+
})
|
| 170 |
+
|
| 171 |
+
@admin_router.get("/files", response_class=HTMLResponse, name="admin_files_page")
|
| 172 |
+
async def admin_files_page(request: Request, admin_user: dict = Depends(get_current_admin)):
|
| 173 |
+
if isinstance(admin_user, RedirectResponse): return admin_user
|
| 174 |
+
if not admin_user: return RedirectResponse(url=app.url_path_for("admin_login_page"), status_code=status.HTTP_307_TEMPORARY_REDIRECT)
|
| 175 |
+
|
| 176 |
+
logger.info(f"Admin: Files page accessed by {admin_user.get('email')}.")
|
| 177 |
+
uploaded_file_objects = []
|
| 178 |
+
try:
|
| 179 |
+
for item_name in sorted(os.listdir(FILES_DIR)):
|
| 180 |
+
item_path = FILES_DIR / item_name
|
| 181 |
+
info = get_file_info(item_path)
|
| 182 |
+
if info:
|
| 183 |
+
uploaded_file_objects.append(info)
|
| 184 |
+
except Exception as e:
|
| 185 |
+
logger.error(f"Admin: Error listing files: {e}")
|
| 186 |
+
|
| 187 |
+
return templates.TemplateResponse("admin_files.html", {
|
| 188 |
+
"request": request,
|
| 189 |
+
"files": uploaded_file_objects,
|
| 190 |
+
"admin_user": admin_user,
|
| 191 |
+
"url_for": app.url_path_for
|
| 192 |
+
})
|
| 193 |
+
|
| 194 |
+
@admin_router.post("/files/delete/{filename}", name="admin_delete_file")
|
| 195 |
+
async def admin_delete_file(request: Request, filename: str, admin_user: dict = Depends(verify_admin_auth)):
|
| 196 |
+
logger.info(f"Admin: Attempting to delete file '{filename}' by {admin_user.get('email')}.")
|
| 197 |
+
safe_filename = sanitize_filename(filename)
|
| 198 |
+
file_path = FILES_DIR / safe_filename
|
| 199 |
+
|
| 200 |
+
if not file_path.resolve().is_relative_to(FILES_DIR.resolve()):
|
| 201 |
+
logger.error(f"Admin: Invalid file path for deletion (traversal attempt) '{filename}'.")
|
| 202 |
+
raise HTTPException(status_code=400, detail="Invalid file path for deletion.")
|
| 203 |
+
|
| 204 |
+
if file_path.is_file():
|
| 205 |
+
try:
|
| 206 |
+
file_path.unlink()
|
| 207 |
+
logger.info(f"Admin: File '{filename}' deleted successfully by {admin_user.get('email')}.")
|
| 208 |
+
return RedirectResponse(url=app.url_path_for("admin_files_page") + "?message=File+deleted+successfully", status_code=status.HTTP_303_SEE_OTHER)
|
| 209 |
+
except Exception as e:
|
| 210 |
+
logger.error(f"Admin: Could not delete file '{filename}': {str(e)}")
|
| 211 |
+
raise HTTPException(status_code=500, detail=f"Could not delete file: {str(e)}")
|
| 212 |
+
else:
|
| 213 |
+
logger.warning(f"Admin: File not found for deletion '{filename}'.")
|
| 214 |
+
raise HTTPException(status_code=404, detail="File not found for deletion.")
|
| 215 |
+
|
| 216 |
+
# /admin/logs route and admin_logs_page function removed
|
| 217 |
+
|
| 218 |
+
# --- Main Application Helper Functions (Original) ---
|
| 219 |
+
def sanitize_filename(filename: str) -> str:
|
| 220 |
+
return os.path.basename(filename).strip()
|
| 221 |
+
|
| 222 |
+
# --- Main Application Routes (Original functionality with added logging) ---
|
| 223 |
+
@app.get("/", response_class=HTMLResponse, name="read_root")
|
| 224 |
+
async def read_root(request: Request):
|
| 225 |
+
logger.info(f"Root page accessed by {request.client.host}")
|
| 226 |
+
return templates.TemplateResponse("index.html", {"request": request, "url_for": app.url_path_for})
|
| 227 |
+
|
| 228 |
+
@app.post("/upload/", name="upload_file")
|
| 229 |
+
async def upload_file(request: Request, file: UploadFile = File(...)):
|
| 230 |
+
original_filename = file.filename
|
| 231 |
+
logger.info(f"Upload attempt for '{original_filename}' from {request.client.host}")
|
| 232 |
+
|
| 233 |
+
if not original_filename:
|
| 234 |
+
logger.warning(f"Upload failed: No filename provided by {request.client.host}")
|
| 235 |
+
raise HTTPException(status_code=400, detail="No filename provided.")
|
| 236 |
+
|
| 237 |
+
filename = sanitize_filename(original_filename)
|
| 238 |
+
if not filename:
|
| 239 |
+
logger.warning(f"Upload failed: Invalid filename '{original_filename}' after sanitization by {request.client.host}")
|
| 240 |
+
raise HTTPException(status_code=400, detail="Invalid filename after sanitization.")
|
| 241 |
+
|
| 242 |
+
file_path = FILES_DIR / filename
|
| 243 |
+
|
| 244 |
+
if not file_path.resolve().is_relative_to(FILES_DIR.resolve()):
|
| 245 |
+
logger.error(f"Upload security violation: Attempted directory traversal for '{filename}' by {request.client.host}")
|
| 246 |
+
raise HTTPException(status_code=400, detail="Invalid file path (attempted directory traversal).")
|
| 247 |
+
|
| 248 |
+
try:
|
| 249 |
+
async with aiofiles.open(file_path, "wb") as buffer:
|
| 250 |
+
while content := await file.read(1024 * 1024):
|
| 251 |
+
await buffer.write(content)
|
| 252 |
+
file_size = file_path.stat().st_size
|
| 253 |
+
logger.info(f"File '{filename}' uploaded successfully by {request.client.host}. Size: {file_size} bytes.")
|
| 254 |
+
except Exception as e:
|
| 255 |
+
logger.error(f"Could not save file '{filename}' from {request.client.host}: {str(e)}")
|
| 256 |
+
if file_path.exists():
|
| 257 |
+
try:
|
| 258 |
+
file_path.unlink()
|
| 259 |
+
logger.info(f"Cleaned up partially uploaded file '{filename}'.")
|
| 260 |
+
except Exception as unlink_e:
|
| 261 |
+
logger.error(f"Error cleaning up partially uploaded file '{filename}': {unlink_e}")
|
| 262 |
+
raise HTTPException(status_code=500, detail=f"Could not save file: {str(e)}")
|
| 263 |
+
|
| 264 |
+
return JSONResponse(
|
| 265 |
+
content={
|
| 266 |
+
"message": "File uploaded successfully",
|
| 267 |
+
"filename": filename,
|
| 268 |
+
"download_url": app.url_path_for("download_file", filename=filename)
|
| 269 |
+
}
|
| 270 |
+
)
|
| 271 |
+
|
| 272 |
+
@app.get("/download/{filename}", name="download_file")
|
| 273 |
+
async def download_file(request: Request, filename: str):
|
| 274 |
+
clean_filename = sanitize_filename(filename)
|
| 275 |
+
logger.info(f"Download attempt for '{clean_filename}' by {request.client.host}")
|
| 276 |
+
|
| 277 |
+
if not clean_filename:
|
| 278 |
+
logger.warning(f"Download failed: Invalid filename '{filename}' by {request.client.host}")
|
| 279 |
+
raise HTTPException(status_code=400, detail="Invalid filename.")
|
| 280 |
+
|
| 281 |
+
file_path = FILES_DIR / clean_filename
|
| 282 |
+
|
| 283 |
+
if not file_path.resolve().is_relative_to(FILES_DIR.resolve()) or not file_path.is_file():
|
| 284 |
+
logger.warning(f"Download failed: File not found or access denied for '{clean_filename}' by {request.client.host}")
|
| 285 |
+
raise HTTPException(status_code=404, detail="File not found or access denied.")
|
| 286 |
+
|
| 287 |
+
logger.info(f"File '{clean_filename}' downloaded by {request.client.host}")
|
| 288 |
+
return FileResponse(path=file_path, filename=clean_filename, media_type='application/octet-stream')
|
| 289 |
+
|
| 290 |
+
app.include_router(admin_router)
|
| 291 |
+
logger.info("Admin panel router included. File-based logging is disabled.")
|
| 292 |
+
|
| 293 |
+
if __name__ == "__main__":
|
| 294 |
+
import uvicorn
|
| 295 |
+
logger.info("Starting Uvicorn server for local development...")
|
| 296 |
uvicorn.run("app:app", host="0.0.0.0", port=7860, reload=True)
|