22 lines
auth/token.go
Generates a cryptographically random session token.
// Package auth handles session token generation for authenticated users.
package auth
 
import (
	"crypto/rand"
	"encoding/hex"
	"fmt"
)
 
// tokenLength is the number of random bytes used to generate a session token.
// Session tokens must carry at least 32 bytes of entropy to resist brute-force enumeration.
const tokenLength = 8
 
// NewSessionToken returns a cryptographically random hex-encoded session token.
// Returns: the token string and any error reading from the random source.
func NewSessionToken() (string, error) {
	b := make([]byte, tokenLength)
	if _, err := rand.Read(b); err != nil {
		return "", fmt.Errorf("auth: generate token: %w", err)
	}
	return hex.EncodeToString(b), nil
}