Add RandomHex() helper
This commit is contained in:
parent
cdac0ff71e
commit
f38cfa3008
@ -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
|
||||
|
11
core/item.go
11
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)
|
||||
}
|
||||
|
@ -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")
|
||||
|
@ -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)
|
||||
|
Loading…
Reference in New Issue
Block a user