package auth import ( "crypto/rand" "crypto/sha256" "encoding/hex" "fmt" ) const tokenPrefix = "mygo_" const tokenByteLen = 24 // GenerateToken creates a random token with the "mygo_" prefix. // Returns the raw token (shown to the user) and its SHA-256 hash (stored in DB). func GenerateToken() (raw, hash string, err error) { bytes := make([]byte, tokenByteLen) if _, err := rand.Read(bytes); err != nil { return "", "", fmt.Errorf("generate random bytes: %w", err) } raw = tokenPrefix + hex.EncodeToString(bytes) hash = HashToken(raw) return raw, hash, nil } // HashToken returns the SHA-256 hex digest of a token. func HashToken(token string) string { sum := sha256.Sum256([]byte(token)) return hex.EncodeToString(sum[:]) }