Spaces:
Sleeping
Sleeping
Soumik Bose commited on
Commit ·
3012e93
1
Parent(s): cdee413
ok
Browse filesFiles changed (4)
123483 unmodified lines8889909192939495import shutilfrom contextlib import asynccontextmanagerfrom fastapi import FastAPI, Depends, Query, HTTPExceptionfrom fastapi.middleware.cors import CORSMiddleware83 unmodified linesfile_path = file_service.get_file_path(fileid)logger.info(f"Serving file: {db_record.filename} ({fileid})")return FileResponse(path=file_path,filename=db_record.filename,media_type="application/octet-stream")1234583 unmodified lines8990919293949596979899100101102import shutilimport mimetypesfrom contextlib import asynccontextmanagerfrom fastapi import FastAPI, Depends, Query, HTTPExceptionfrom fastapi.middleware.cors import CORSMiddleware83 unmodified linesfile_path = file_service.get_file_path(fileid)logger.info(f"Serving file: {db_record.filename} ({fileid})")mime_type = file_service.get_mime_type(db_record.filename)headers = {"Content-Disposition": f'inline; filename="{db_record.filename}"'}return FileResponse(path=file_path,media_type=mime_type or "application/octet-stream",headers=headers)
11 unmodified lines1213141516171819202122232411 unmodified linesresponse.headers["X-XSS-Protection"] = "1; mode=block"response.headers["Referrer-Policy"] = "strict-origin-when-cross-origin"response.headers["Permissions-Policy"] = "geolocation=(), microphone=(), camera=()"response.headers["Content-Security-Policy"] = ("default-src 'self'; ""script-src 'self'; ""style-src 'self'; ""img-src 'self' data:; ""object-src 'none';")response.headers["Cache-Control"] = "no-store"response.headers["Pragma"] = "no-cache"return response11 unmodified lines1213141516171819202122232425262711 unmodified linesresponse.headers["X-XSS-Protection"] = "1; mode=block"response.headers["Referrer-Policy"] = "strict-origin-when-cross-origin"response.headers["Permissions-Policy"] = "geolocation=(), microphone=(), camera=()"# Relax CSP for file rendering (e.g., PDFs and images)response.headers["Content-Security-Policy"] = ("default-src 'self'; ""script-src 'self'; ""style-src 'self'; ""img-src 'self' data: *; ""object-src 'self' *;")# For file serving, we might want to allow caching, but for now we just ensure it doesn't force downloadif not request.url.path.startswith("/v1/getfile"):response.headers["Cache-Control"] = "no-store"response.headers["Pragma"] = "no-cache"return response
53 unmodified lines545556575859606162636453 unmodified linesfile_path = file_service.get_file_path(fileid)mime_type, _ = mimetypes.guess_type(db_record.filename)return FileResponse(path=file_path,media_type=mime_type or "application/octet-stream",filename=db_record.filename,content_disposition_type="inline")53 unmodified lines5455565758596061626364656667686970717253 unmodified linesfile_path = file_service.get_file_path(fileid)mime_type = file_service.get_mime_type(db_record.filename)# If we want the browser to render the file (inline), we should set the media_type# and use content_disposition_type="inline".# Note: Some browsers might still download if 'filename' is provided in the header.# To maximize compatibility with "render in browser", we ensure the media_type is correct.headers = {"Content-Disposition": f'inline; filename="{db_record.filename}"'}return FileResponse(path=file_path,media_type=mime_type or "application/octet-stream",headers=headers)
1 unmodified line2345674 unmodified lines121314151617104 unmodified lines1221231241251 unmodified lineimport uuidimport shutilfrom pathlib import Pathfrom sqlalchemy.orm import Sessionfrom fastapi import UploadFile, HTTPExceptionfrom app.core.config import settings4 unmodified lineslogger = get_logger(__name__)class FileService:def __init__(self):self.files_dir = Path(settings.FILES_DIR)self.files_dir.mkdir(parents=True, exist_ok=True)104 unmodified linesraise HTTPException(status_code=404, detail="File not found on disk")return file_pathfile_service = FileService()1 unmodified line23456784 unmodified lines1314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374104 unmodified lines1791801811821831841851861871881891901911921931941951961 unmodified lineimport uuidimport shutilfrom pathlib import Pathimport mimetypesfrom sqlalchemy.orm import Sessionfrom fastapi import UploadFile, HTTPExceptionfrom app.core.config import settings4 unmodified lineslogger = get_logger(__name__)class FileService:# Custom MIME type mapping for common browser-renderable files# This helps ensure that files are rendered inline when possible, even if mimetypes.guess_type is generic.RENDERABLE_MIME_TYPES = {# Images'.png': 'image/png','.jpg': 'image/jpeg','.jpeg': 'image/jpeg','.gif': 'image/gif','.webp': 'image/webp','.svg': 'image/svg+xml','.apng': 'image/apng','.avif': 'image/avif','.bmp': 'image/bmp','.ico': 'image/vnd.microsoft.icon','.tif': 'image/tiff','.tiff': 'image/tiff',# Audio'.aac': 'audio/aac','.mp3': 'audio/mpeg','.oga': 'audio/ogg','.ogg': 'audio/ogg','.wav': 'audio/wav','.weba': 'audio/webm','.midi': 'audio/midi','.mid': 'audio/midi',# Video'.mp4': 'video/mp4','.mpeg': 'video/mpeg','.ogv': 'video/ogg','.webm': 'video/webm','.ts': 'video/mp2t',# Documents & Text'.pdf': 'application/pdf','.txt': 'text/plain','.html': 'text/html','.htm': 'text/html','.css': 'text/css','.js': 'text/javascript','.json': 'application/json','.jsonld': 'application/ld+json','.md': 'text/markdown','.xml': 'application/xml','.xhtml': 'application/xhtml+xml','.csv': 'text/csv','.ics': 'text/calendar',# Fonts (browsers can render these if linked, but serving them inline might just show binary or trigger download)'.otf': 'font/otf','.ttf': 'font/ttf','.woff': 'font/woff','.woff2': 'font/woff2',}def __init__(self):self.files_dir = Path(settings.FILES_DIR)self.files_dir.mkdir(parents=True, exist_ok=True)104 unmodified linesraise HTTPException(status_code=404, detail="File not found on disk")return file_pathdef get_mime_type(self, filename: str) -> str:# First, try to get MIME type from our custom mappingfile_extension = Path(filename).suffix.lower()if file_extension in self.RENDERABLE_MIME_TYPES:return self.RENDERABLE_MIME_TYPES[file_extension]# If not in custom mapping, try mimetypes.guess_typemime_type, _ = mimetypes.guess_type(filename)if mime_type:return mime_type# Fallback to a generic binary stream if type is still unknownreturn "application/octet-stream"file_service = FileService()
app/main.py+9-2
app/middleware/security_headers.py+7-4
app/routers/files.py+11-3
app/services/file_service.py+71