Skip to content

Commit

Permalink
fix: simplify uploaded file names
Browse files Browse the repository at this point in the history
  • Loading branch information
fsrv-xyz committed Oct 11, 2023
2 parents 35b7329 + 5cd6c5f commit 5d6f2b3
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 0 deletions.
1 change: 1 addition & 0 deletions handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,7 @@ func (c *Config) UploadHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
filename, ok := vars["filename"]
filename = url.QueryEscape(filename)
filename = onlyAllowedCharacters(filename)

if cancelRequestIfUnhealthy(w) {
return
Expand Down
6 changes: 6 additions & 0 deletions helper.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"mime"
"net/http"
"path"
"regexp"
"runtime"
"time"

Expand Down Expand Up @@ -61,3 +62,8 @@ func traceLog(logger *log.Logger, msg interface{}) {
logger.Printf("%v @ %v:%d | %v", details.Name(), path.Base(file), line, msg)
}
}

func onlyAllowedCharacters(s string) string {
gex := regexp.MustCompile(`[^a-zA-Z.0-9_-]`)
return gex.ReplaceAllString(s, "")
}
36 changes: 36 additions & 0 deletions helper_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,3 +31,39 @@ func TestSelectContentType(t *testing.T) {
})
}
}

func Test_onlyAllowedCharacters(t *testing.T) {
for _, test := range []struct {
Name string
Filename string
Expected string
}{
{
Name: "allowed characters",
Filename: "test.txt",
Expected: "test.txt",
},
{
Name: "not allowed characters",
Filename: "test (1).txt",
Expected: "test1.txt",
},
{
Name: "not allowed characters with spaces",
Filename: "test foo bar.txt",
Expected: "testfoobar.txt",
},
{
Name: "capital letters",
Filename: "Test.txt",
Expected: "Test.txt",
},
} {
t.Run(test.Name, func(t *testing.T) {
result := onlyAllowedCharacters(test.Filename)
if result != test.Expected {
t.Errorf("%+q is expected but %+q is resulting\n", test.Expected, result)
}
})
}
}

0 comments on commit 5d6f2b3

Please sign in to comment.