Add RandomHex() helper

This commit is contained in:
Tim Van Baak 2025-02-10 06:36:13 -08:00
parent cdac0ff71e
commit f38cfa3008
4 changed files with 16 additions and 17 deletions

View File

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

View File

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

View File

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

View File

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