Drag and Drop UI: Modifies the SanitizePath approach for path handed over from dropzone.js. Add tests to check the algorithm.

This commit is contained in:
David Rotermund 2025-04-04 01:43:23 +02:00
parent 8f5c3b2227
commit 4383c403c9
3 changed files with 105 additions and 34 deletions

View file

@ -0,0 +1,39 @@
package files
import (
"fmt"
"path"
"regexp"
"strings"
)
var fileNameComponentSanitizeRegexp = regexp.MustCompile(`(?i)\.\.|[<>:\"/\\|?*\x{0000}-\x{001F}]|^(con|prn|aux|nul|com\d|lpt\d)$`)
// SanitizePath cleans and validates a file path
func SanitizePath(inputPath string) (string, error) {
// Normalize path separators
s := strings.ReplaceAll(inputPath, "\\", "/")
// Clean the path
s = path.Clean(s)
// Split the path components
pathComponents := strings.Split(s, "/")
// Sanitize each path component
var sanitizedComponents []string
for _, component := range pathComponents {
// Trim whitespace and apply regex sanitization
sanitizedComponent := strings.TrimSpace(fileNameComponentSanitizeRegexp.ReplaceAllString(component, "_"))
// Skip empty components after sanitization
if sanitizedComponent != "" {
sanitizedComponents = append(sanitizedComponents, sanitizedComponent)
}
}
// Check if we have any components left after sanitization
if len(sanitizedComponents) == 0 {
return "", fmt.Errorf("path became empty after sanitization")
}
// Reconstruct the path
reconstructedPath := path.Join(sanitizedComponents...)
return reconstructedPath, nil
}