Imp: Limit somehow the upload file in size and mimetype
This commit is contained in:
parent
5c42ff6851
commit
1ba891eef0
@ -25,13 +25,23 @@ func handleUpload(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
file, _, err := r.FormFile("file")
|
||||
file, fileHeader, err := r.FormFile("file")
|
||||
if err != nil {
|
||||
http.Error(w, "Error reading file", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
isValid, err := isTextFileAndSizeOk(file, fileHeader.Size)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if !isValid {
|
||||
http.Error(w, "Invalid file type or size", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
commandCounts, categories, pipeRedirectionCounts, commonPatterns := ProcessHistory(file)
|
||||
|
||||
limit := os.Getenv("TOP_N_COMMANDS")
|
||||
|
@ -5,7 +5,9 @@ import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"html/template"
|
||||
"io"
|
||||
"log"
|
||||
"mime/multipart"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
@ -166,3 +168,28 @@ func loadTemplatesFromDir(dir string) ([]string, error) {
|
||||
|
||||
return templates, err
|
||||
}
|
||||
|
||||
func isTextFileAndSizeOk(file multipart.File, size int64) (bool, error) {
|
||||
if size > 1*1024*1024 {
|
||||
return false, fmt.Errorf("File size exceeds 1MB")
|
||||
}
|
||||
|
||||
buffer := make([]byte, 512)
|
||||
_, err := file.Read(buffer)
|
||||
if err != nil && err != io.EOF {
|
||||
return false, fmt.Errorf("Error reading file: %v", err)
|
||||
}
|
||||
|
||||
mimeType := http.DetectContentType(buffer)
|
||||
|
||||
if !strings.HasPrefix(mimeType, "text/") {
|
||||
return false, fmt.Errorf("File is not a text file (mimetype: %s)", mimeType)
|
||||
}
|
||||
|
||||
_, err = file.Seek(0, 0)
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("Error seeking file: %v", err)
|
||||
}
|
||||
|
||||
return true, nil
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user