From 9570e339a39aacd0bed635208e94adc59f14fb4c Mon Sep 17 00:00:00 2001 From: Ada Date: Sun, 18 Feb 2024 23:27:14 +0100 Subject: [PATCH] :sparkles: Support filename --- internal/utils/utils.go | 11 +++++++++++ internal/web/plak/plak.go | 20 +++++++++++++++++++- test/utils/utils_test.go | 18 ++++++++++++++++++ 3 files changed, 48 insertions(+), 1 deletion(-) diff --git a/internal/utils/utils.go b/internal/utils/utils.go index fe3369d..e3a98b1 100644 --- a/internal/utils/utils.go +++ b/internal/utils/utils.go @@ -5,6 +5,7 @@ import ( "encoding/hex" "log" mathrand "math/rand/v2" + "regexp" "strconv" "strings" ) @@ -99,3 +100,13 @@ func ParseExpiration(source string) (int, error) { return expiration, nil } + +// ValidKey Verify if a key is valid (only letter, number, - and _) +func ValidKey(key string) bool { + result, err := regexp.MatchString("^[a-zA-Z0-9_.-]*$", key) + if err != nil { + return false + } + log.Println(key, result) + return result +} diff --git a/internal/web/plak/plak.go b/internal/web/plak/plak.go index 51b8af6..f7fbe7c 100644 --- a/internal/web/plak/plak.go +++ b/internal/web/plak/plak.go @@ -36,18 +36,36 @@ func (config WebConfig) Create(w http.ResponseWriter, r *http.Request) { content := r.FormValue("content") if content == "" { w.WriteHeader(http.StatusBadRequest) + return } dbConf := database.DBConfig{ DB: config.DB, } + filename := r.FormValue("filename") + var key string + if len(filename) == 0 { + key = utils.GenerateUrl(config.UrlLength) + } else { + if !utils.ValidKey(filename) { + w.WriteHeader(http.StatusBadRequest) + return + } + if dbConf.UrlExist(filename) { + w.WriteHeader(http.StatusBadRequest) + return + } + key = filename + } + secret := utils.GenerateSecret() - key := utils.GenerateUrl(config.UrlLength) rawExpiration := r.FormValue("exp") + expiration, err := utils.ParseExpiration(rawExpiration) if err != nil { w.WriteHeader(http.StatusBadRequest) + return } else if expiration == 0 { dbConf.InsertPaste(key, content, secret, -1) } else { diff --git a/test/utils/utils_test.go b/test/utils/utils_test.go index 1752121..f2a87b6 100644 --- a/test/utils/utils_test.go +++ b/test/utils/utils_test.go @@ -79,3 +79,21 @@ func TestParseExpirationInvalidRedundant(t *testing.T) { // test ParseExpiration t.Fatal("Error in ParseExpirationFull, want : ", want, "got : ", got) } } + +func TestValidKey(t *testing.T) { // test ValidKey with a valid key + got := utils.ValidKey("ab_a-C42") + want := true + + if got != want { + t.Fatal("Error in ValidKey, want : ", want, "got : ", got) + } +} + +func TestInValidKey(t *testing.T) { // test ValidKey with invalid key + got := utils.ValidKey("ab_?a-C42") + want := false + + if got != want { + t.Fatal("Error in ValidKey, want : ", want, "got : ", got) + } +}