small pixel drawing of a pufferfish vore

reuse session_token across sessions so that you dont log urself out
Jes Olson j3s@c3f.net
Sun, 09 Jul 2023 17:27:36 -0500
commit

07825b21d809294b4bee2845d4362a1e55e7b709

parent

3418e810abf1ba41e1a571d8ed82d7003e2fa32a

3 files changed, 19 insertions(+), 10 deletions(-)

jump to
M lib/token.golib/token.go

@@ -5,12 +5,7 @@ "crypto/rand"

"encoding/hex" ) -func GenerateSessionToken() string { - // 32 bytes == 256 bits (AES security margin is 128 bits) - return generateSecureToken(32) -} - -func generateSecureToken(length int) string { +func GenerateSecureToken(length int) string { b := make([]byte, length) if _, err := rand.Read(b); err != nil { return ""
M site.gosite.go

@@ -275,12 +275,17 @@ err := bcrypt.CompareHashAndPassword([]byte(storedPassword), []byte(password))

if err != nil { return fmt.Errorf("invalid password") } - sessionToken := lib.GenerateSessionToken() - err = s.db.SetSessionToken(username, sessionToken) + sessionToken, err := s.db.GetSessionToken(username) if err != nil { - log.Println(err) + return err + } + if sessionToken == "" { + sessionToken = lib.GenerateSecureToken(32) + err := s.db.SetSessionToken(username, sessionToken) + if err != nil { + return err + } } - http.SetCookie(w, &http.Cookie{ Name: "session_token", Expires: time.Now().Add(time.Hour * 24 * 365),
M sqlite/sql.gosqlite/sql.go

@@ -78,6 +78,15 @@ }

return password } +func (db *DB) GetSessionToken(username string) (string, error) { + var result sql.NullString + err := db.sql.QueryRow("SELECT session_token FROM user WHERE username=?", username).Scan(&result) + if err == sql.ErrNoRows { + return "", nil + } + return result.String, err +} + func (db *DB) SetSessionToken(username string, token string) error { _, err := db.sql.Exec("UPDATE user SET session_token=? WHERE username=?", token, username) return err