Files
mtusi2026lab5/internal/auth/session.go
T

40 lines
1.1 KiB
Go

// Package auth authenticates callers.
//
// A login with Basic credentials creates a server-side session and returns an
// opaque bearer token; every protected request presents the token, and logout
// deletes the session, which revokes the token at once. The store keeps only
// the SHA-256 of a token: a token is a random 256-bit value, so a fast digest
// cannot be reversed by guessing, and a leaked store yields no usable tokens.
// Passwords need the opposite treatment (a slow KDF), see platform/password.
package auth
import (
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"time"
"github.com/google/uuid"
)
type Session struct {
TokenHash string
UserID uuid.UUID
ExpiresAt time.Time
}
// newToken returns 32 random bytes in base64url: 43 characters, 256 bits.
func newToken() string {
raw := make([]byte, 32)
// Since Go 1.24 crypto/rand.Read never returns an error.
_, _ = rand.Read(raw)
return base64.RawURLEncoding.EncodeToString(raw)
}
// HashToken is the key under which a token's session is stored.
func HashToken(token string) string {
sum := sha256.Sum256([]byte(token))
return hex.EncodeToString(sum[:])
}