Drop narration, history and restated-code comments across the repo, keep short ones for security boundaries, upstream quirks and ordering constraints, and record the convention in CLAUDE.md. Co-Authored-By: Claude Opus 5.5 <[email protected]>
70 lines
1.9 KiB
Go
70 lines
1.9 KiB
Go
package handlers
|
|
|
|
import (
|
|
"errors"
|
|
"log"
|
|
"net/http"
|
|
|
|
"adam-french.co.uk/backend/services"
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/golang-jwt/jwt/v5"
|
|
)
|
|
|
|
// Upload stores a multipart `file` via services.Uploads.Save and returns its
|
|
// URL. `private` is admin-only, as private messages are.
|
|
func (store *Store) Upload(ctx *gin.Context) {
|
|
private := ctx.PostForm("private") == "true"
|
|
if private && !requestIsAdmin(ctx) {
|
|
ctx.JSON(http.StatusForbidden, gin.H{"error": "admin access required"})
|
|
return
|
|
}
|
|
|
|
file, err := ctx.FormFile("file")
|
|
if err != nil {
|
|
ctx.JSON(http.StatusBadRequest, gin.H{"error": "file is required"})
|
|
return
|
|
}
|
|
|
|
url, err := store.Uploads.Save(ctx.Request.Context(), file, private)
|
|
var rejected *services.UploadError
|
|
switch {
|
|
case errors.As(err, &rejected):
|
|
ctx.JSON(http.StatusBadRequest, gin.H{"error": rejected.Message})
|
|
case err != nil:
|
|
log.Printf("[upload] storing %s failed: %v", file.Filename, err)
|
|
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to save file"})
|
|
default:
|
|
ctx.JSON(http.StatusOK, gin.H{"url": url})
|
|
}
|
|
}
|
|
|
|
// ListUploads is admin-only: listing is what turns unguessable URLs into known ones.
|
|
func (store *Store) ListUploads(ctx *gin.Context) {
|
|
files, err := store.Uploads.List(ctx.Request.Context())
|
|
if err != nil {
|
|
log.Printf("[upload] listing failed: %v", err)
|
|
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to list uploads"})
|
|
return
|
|
}
|
|
if files == nil {
|
|
files = []services.StoredFile{} // [] rather than null for the frontend
|
|
}
|
|
ctx.JSON(http.StatusOK, gin.H{"files": files})
|
|
}
|
|
|
|
// requestIsAdmin: this route is in `protected`, not `admin`, since any
|
|
// signed-in user may upload public files.
|
|
func requestIsAdmin(ctx *gin.Context) bool {
|
|
claims, exists := ctx.Get("userClaims")
|
|
if !exists {
|
|
return false
|
|
}
|
|
mapClaims, ok := claims.(*jwt.MapClaims)
|
|
if !ok {
|
|
return false
|
|
}
|
|
admin, ok := (*mapClaims)["admin"].(bool)
|
|
|
|
return ok && admin
|
|
}
|