From 15ae483fadbd136acefcd602b2f2ac5a83165c73 Mon Sep 17 00:00:00 2001 From: Brian Picciano Date: Sun, 29 Aug 2021 22:15:58 -0600 Subject: add CSRF checking --- srv/api/utils.go | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) (limited to 'srv/api/utils.go') diff --git a/srv/api/utils.go b/srv/api/utils.go index 7662e17..2cf40b6 100644 --- a/srv/api/utils.go +++ b/srv/api/utils.go @@ -2,7 +2,11 @@ package api import ( "context" + "crypto/rand" + "encoding/hex" "encoding/json" + "errors" + "fmt" "net/http" "strconv" @@ -66,3 +70,22 @@ func strToInt(str string, defaultVal int) (int, error) { } return strconv.Atoi(str) } + +func getCookie(r *http.Request, cookieName, defaultVal string) (string, error) { + c, err := r.Cookie(cookieName) + if errors.Is(err, http.ErrNoCookie) { + return defaultVal, nil + } else if err != nil { + return "", fmt.Errorf("reading cookie %q: %w", cookieName, err) + } + + return c.Value, nil +} + +func randStr(numBytesEntropy int) string { + b := make([]byte, numBytesEntropy) + if _, err := rand.Read(b); err != nil { + panic(err) + } + return hex.EncodeToString(b) +} -- cgit v1.2.3