upload-service/internal/handler/download.go

55 lines
1.1 KiB
Go

package handler
import (
"database/sql"
"log"
"net/http"
"time"
)
func (h *Handler) Download(w http.ResponseWriter, r *http.Request) {
id := r.PathValue("id")
if id == "" {
http.NotFound(w, r)
return
}
rec, err := h.store.Get(id)
if err == sql.ErrNoRows {
http.NotFound(w, r)
return
}
if err != nil {
log.Printf("db get error: %v", err)
http.Error(w, "internal error", http.StatusInternalServerError)
return
}
// Check expiry
if rec.ExpiresAt != nil && rec.ExpiresAt.Before(time.Now().UTC()) {
http.Error(w, "this file has expired", http.StatusGone)
return
}
// Check password
if rec.PasswordHash != nil {
cookie, err := r.Cookie("auth_" + id)
if err != nil || cookie.Value != "granted" {
http.Redirect(w, r, "/f/"+id+"/auth", http.StatusSeeOther)
return
}
}
// Generate presigned URL
url, err := h.r2.PresignGet(r.Context(), rec.R2Key, rec.Filename)
if err != nil {
log.Printf("presign error: %v", err)
http.Error(w, "internal error", http.StatusInternalServerError)
return
}
h.store.IncrementDownloads(id)
http.Redirect(w, r, url, http.StatusFound)
}