From f38cfa3008543b6ec98a9ed725eacf68f811a281 Mon Sep 17 00:00:00 2001 From: Tim Van Baak Date: Mon, 10 Feb 2025 06:36:13 -0800 Subject: [PATCH] Add RandomHex() helper --- cmd/itemAdd.go | 8 +------- core/item.go | 11 +++++++++++ web/item.go | 8 +------- web/login.go | 6 +++--- 4 files changed, 16 insertions(+), 17 deletions(-) diff --git a/cmd/itemAdd.go b/cmd/itemAdd.go index 804bb5f..d8fbddc 100644 --- a/cmd/itemAdd.go +++ b/cmd/itemAdd.go @@ -1,8 +1,6 @@ package cmd import ( - "crypto/rand" - "encoding/hex" "encoding/json" "log" @@ -70,11 +68,7 @@ func itemAdd( } // Default id to random hex string if id == "" { - bytes := make([]byte, 16) - if _, err := rand.Read(bytes); err != nil { - log.Fatalf("error: failed to generate id: %v", err) - } - id = hex.EncodeToString(bytes) + id = core.RandomHex(16) } var itemActions core.Actions diff --git a/core/item.go b/core/item.go index 50896b4..583c030 100644 --- a/core/item.go +++ b/core/item.go @@ -5,6 +5,7 @@ import ( "encoding/json" "fmt" "log" + "math/rand" "time" ) @@ -105,3 +106,13 @@ var AvailableFormats = map[string]string{ "json": "Full item JSON", "short": "Item source and id", } + +const hexDigits = "0123456789abcdef" + +func RandomHex(n int) string { + bytes := make([]byte, n) + for i := range bytes { + bytes[i] = hexDigits[rand.Intn(len(hexDigits))] + } + return string(bytes) +} diff --git a/web/item.go b/web/item.go index 2221033..0c402b7 100644 --- a/web/item.go +++ b/web/item.go @@ -1,8 +1,6 @@ package web import ( - "crypto/rand" - "encoding/hex" "fmt" "log" "net/http" @@ -157,11 +155,7 @@ func (env *Env) addItem(writer http.ResponseWriter, req *http.Request) { } } - bytes := make([]byte, 16) - if _, err := rand.Read(bytes); err != nil { - http.Error(writer, fmt.Sprintf("error: failed to generate id: %v", err), 500) - } - id := hex.EncodeToString(bytes) + id := core.RandomHex(16) title := req.PostForm.Get("title") link := req.PostForm.Get("link") diff --git a/web/login.go b/web/login.go index 273cca4..82cf827 100644 --- a/web/login.go +++ b/web/login.go @@ -15,13 +15,13 @@ import ( var AuthCookieName string = "intake_auth" var AuthDuration time.Duration = time.Hour * 24 * 7 -func newSession(db core.DB) (string, error) { +func newSession(db core.DB) (session string, err error) { bytes := make([]byte, 32) - _, err := rand.Read(bytes) + _, err = rand.Read(bytes) if err != nil { return "", err } - session := fmt.Sprintf("%x", bytes) + session = fmt.Sprintf("%x", bytes) expires := int(time.Now().Add(AuthDuration).Unix()) _, err = db.Exec(` insert into sessions (id, expires)