Support filename

This commit is contained in:
Ada 2024-02-18 23:27:14 +01:00
parent 6ea5e8cdfc
commit d4806f98e8
3 changed files with 48 additions and 1 deletions

View file

@ -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
}

View file

@ -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 {

View file

@ -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)
}
}