2024-09-01 18:16:09 +02:00
|
|
|
package frontend
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"log"
|
|
|
|
"net/http"
|
|
|
|
"path/filepath"
|
|
|
|
|
|
|
|
"github.com/google/uuid"
|
|
|
|
b "streifling.com/jason/cpolis/cmd/backend"
|
|
|
|
)
|
|
|
|
|
|
|
|
func UploadPDF(c *b.Config, s *b.CookieStore) http.HandlerFunc {
|
|
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
2024-10-30 03:24:29 +01:00
|
|
|
if _, err := GetSession(w, r, c, s); err != nil {
|
2024-10-04 10:35:32 +02:00
|
|
|
log.Println(err)
|
|
|
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
2024-09-01 18:16:09 +02:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
file, _, err := r.FormFile("pdf-upload")
|
|
|
|
if err != nil {
|
|
|
|
log.Println(err)
|
|
|
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
defer file.Close()
|
|
|
|
|
2024-10-04 16:06:33 +02:00
|
|
|
buffer := make([]byte, 512) // Should be enough for mime type
|
|
|
|
if _, err := file.Read(buffer); err != nil {
|
|
|
|
log.Println(err)
|
|
|
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
if _, err := file.Seek(0, 0); err != nil {
|
|
|
|
log.Println(err)
|
|
|
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
if http.DetectContentType(buffer) != "application/pdf" {
|
2024-10-04 16:46:29 +02:00
|
|
|
http.Error(w, "Die Datei ist kein PDF.", http.StatusBadRequest)
|
2024-10-04 16:06:33 +02:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2024-09-01 18:16:09 +02:00
|
|
|
filename := fmt.Sprint(uuid.New(), ".pdf")
|
2024-10-04 16:37:19 +02:00
|
|
|
absFilepath, err := filepath.Abs(c.PDFDir + "/" + filename)
|
2024-09-01 18:16:09 +02:00
|
|
|
if err != nil {
|
|
|
|
log.Println(err)
|
|
|
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2024-10-04 16:36:53 +02:00
|
|
|
if err = b.WriteFile(absFilepath, file); err != nil {
|
2024-09-01 18:16:09 +02:00
|
|
|
log.Println(err)
|
|
|
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
w.WriteHeader(http.StatusOK)
|
|
|
|
}
|
|
|
|
}
|