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
3 files changed,
19 insertions(+),
10 deletions(-)
M
lib/token.go
→
lib/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.go
→
site.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.go
→
sqlite/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