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 package cmd
import ( import (
"crypto/rand"
"encoding/hex"
"encoding/json" "encoding/json"
"log" "log"
@ -70,11 +68,7 @@ func itemAdd(
} }
// Default id to random hex string // Default id to random hex string
if id == "" { if id == "" {
bytes := make([]byte, 16) id = core.RandomHex(16)
if _, err := rand.Read(bytes); err != nil {
log.Fatalf("error: failed to generate id: %v", err)
}
id = hex.EncodeToString(bytes)
} }
var itemActions core.Actions var itemActions core.Actions

View File

@ -5,6 +5,7 @@ import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"log" "log"
"math/rand"
"time" "time"
) )
@ -105,3 +106,13 @@ var AvailableFormats = map[string]string{
"json": "Full item JSON", "json": "Full item JSON",
"short": "Item source and id", "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 package web
import ( import (
"crypto/rand"
"encoding/hex"
"fmt" "fmt"
"log" "log"
"net/http" "net/http"
@ -157,11 +155,7 @@ func (env *Env) addItem(writer http.ResponseWriter, req *http.Request) {
} }
} }
bytes := make([]byte, 16) id := core.RandomHex(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)
title := req.PostForm.Get("title") title := req.PostForm.Get("title")
link := req.PostForm.Get("link") link := req.PostForm.Get("link")

View File

@ -15,13 +15,13 @@ import (
var AuthCookieName string = "intake_auth" var AuthCookieName string = "intake_auth"
var AuthDuration time.Duration = time.Hour * 24 * 7 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) bytes := make([]byte, 32)
_, err := rand.Read(bytes) _, err = rand.Read(bytes)
if err != nil { if err != nil {
return "", err return "", err
} }
session := fmt.Sprintf("%x", bytes) session = fmt.Sprintf("%x", bytes)
expires := int(time.Now().Add(AuthDuration).Unix()) expires := int(time.Now().Add(AuthDuration).Unix())
_, err = db.Exec(` _, err = db.Exec(`
insert into sessions (id, expires) insert into sessions (id, expires)