code refactoring, added file download (#118)

This commit is contained in:
Marco
2023-12-27 15:08:51 +01:00
committed by GitHub
parent c5535fad71
commit 3859c80214
5 changed files with 82 additions and 39 deletions

View File

@@ -3,6 +3,7 @@ package handlers
import (
"encoding/base64"
"encoding/json"
"io"
"net/http"
"net/url"
"os"
@@ -136,14 +137,55 @@ func SendFile(w http.ResponseWriter, r *http.Request) {
// TODO: further path / file validations
if strings.Contains(filepath.Dir(filename), root) {
w.Header().Add(
"Content-Disposition",
"inline; filename="+filepath.Base(filename),
)
http.ServeFile(w, r, filename)
return
}
w.WriteHeader(http.StatusUnauthorized)
}
func DownloadFile(w http.ResponseWriter, r *http.Request) {
path := chi.URLParam(r, "id")
if path == "" {
http.Error(w, "inexistent path", http.StatusBadRequest)
return
}
path, err := url.QueryUnescape(path)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
decoded, err := base64.StdEncoding.DecodeString(path)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
filename := string(decoded)
root := config.Instance().DownloadPath
if strings.Contains(filepath.Dir(filename), root) {
w.Header().Add(
"Content-Disposition",
"inline; filename="+filepath.Base(filename),
)
w.Header().Set(
"Content-Type",
"application/octet-stream",
)
fd, err := os.Open(filename)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
io.Copy(w, fd)
}
w.WriteHeader(http.StatusUnauthorized)
}