package handlers import ( "crypto/rand" "database/sql" "encoding/hex" "errors" "fmt" "io" "mime/multipart" "net/http" "path/filepath" "strings" "vlog/internal/auth" "vlog/internal/models" "vlog/internal/storage" ) // parseUploadedFile extracts the "file" multipart field, enforces maxBytes, // and sniffs+validates its real content type against allowed (never trusts // the client-declared type/extension). Returns the file handle reset to the // start, ready to stream to storage — caller must Close it. func parseUploadedFile(w http.ResponseWriter, r *http.Request, maxBytes int64, allowed map[string]bool) (multipart.File, string, bool) { r.Body = http.MaxBytesReader(w, r.Body, maxBytes) if err := r.ParseMultipartForm(maxBytes); err != nil { writeError(w, http.StatusBadRequest, "file too large or invalid upload") return nil, "", false } file, _, err := r.FormFile("file") if err != nil { writeError(w, http.StatusBadRequest, "missing file") return nil, "", false } contentType, err := storage.DetectAndValidate(file, allowed) if err != nil { file.Close() writeError(w, http.StatusUnsupportedMediaType, err.Error()) return nil, "", false } return file, contentType, true } func extensionForContentType(ct string) string { switch ct { case "image/png": return "png" case "image/jpeg": return "jpg" case "application/pdf": return "pdf" default: return "bin" } } func contentTypeForExtension(key string) string { switch { case strings.HasSuffix(key, ".png"): return "image/png" case strings.HasSuffix(key, ".jpg"), strings.HasSuffix(key, ".jpeg"): return "image/jpeg" case strings.HasSuffix(key, ".pdf"): return "application/pdf" default: return "application/octet-stream" } } func randomID() string { b := make([]byte, 16) if _, err := rand.Read(b); err != nil { panic(err) } return hex.EncodeToString(b) } // sanitizeFileName strips any path components and whitespace so it's safe // to embed in a storage key and to send back in Content-Disposition. func sanitizeFileName(name string) string { name = filepath.Base(name) name = strings.ReplaceAll(name, " ", "_") if name == "" || name == "." || name == "/" { return "file" } return name } // GetFile streams a service-entry attachment after verifying the requesting // user owns the car the entry belongs to. func (h *Handlers) GetFile(w http.ResponseWriter, r *http.Request) { file, ok := h.loadOwnedFile(w, r) if !ok { return } body, err := h.Storage.Get(r.Context(), file.S3Key) if err != nil { writeError(w, http.StatusNotFound, "file not found in storage") return } defer body.Close() w.Header().Set("Content-Type", file.ContentType) w.Header().Set("Content-Disposition", fmt.Sprintf(`inline; filename="%s"`, file.FileName)) io.Copy(w, body) } // DeleteFile removes a single attachment. func (h *Handlers) DeleteFile(w http.ResponseWriter, r *http.Request) { file, ok := h.loadOwnedFile(w, r) if !ok { return } if _, err := h.dbExec(r.Context(), `DELETE FROM service_entry_files WHERE id = ?`, file.ID); err != nil { writeError(w, http.StatusInternalServerError, "failed to delete file") return } _ = h.Storage.Delete(r.Context(), file.S3Key) writeJSON(w, http.StatusOK, map[string]bool{"ok": true}) } func (h *Handlers) loadOwnedFile(w http.ResponseWriter, r *http.Request) (*models.ServiceEntryFile, bool) { userID, _ := auth.UserIDFromContext(r.Context()) fileID := r.PathValue("fileId") var file models.ServiceEntryFile err := h.dbGet(r.Context(), &file, ` SELECT sef.* FROM service_entry_files sef JOIN service_entries se ON se.id = sef.service_entry_id JOIN cars c ON c.id = se.car_id WHERE sef.id = ? AND c.user_id = ? `, fileID, userID) if errors.Is(err, sql.ErrNoRows) { writeError(w, http.StatusNotFound, "file not found") return nil, false } if err != nil { writeError(w, http.StatusInternalServerError, "failed to load file") return nil, false } return &file, true }