sonda/internal/api/http/middleware.go
tgiachi 3a739dc3ae feat: add sondad server with config, storage, auth and listening API
- feat(config): TOML config with env overrides, strict parsing and validation
- feat(storage): SQLite (modernc) and PostgreSQL (pgx) backends through bun,
  embedded per-driver SQL migrations with a transactional runner
- feat(schema): catalog tables (artists, albums, tracks, audio_files with
  per-root paths), users and listening events with idempotency keys
- feat(auth): Argon2id password hashing, HS256 JWT tokens, first-user-only
  registration and login
- feat(api): gin REST API under /api/v1 (health, register, login, listens)
  with a consistent error envelope, body limit and request logging
- feat(sondad): zap logger, graceful shutdown, composition root in main
- chore: example config, .gitignore for secrets, DB files, IDE and agent files
2026-11-11 12:06:15 +01:00

58 lines
1.4 KiB
Go

package httpapi
import (
"net/http"
"strings"
"time"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
)
const (
ctxUserID = "user_id"
ctxUsername = "username"
)
// limitBody caps the request body size.
func limitBody(max int64) gin.HandlerFunc {
return func(c *gin.Context) {
c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, max)
c.Next()
}
}
// requestLog logs one line per request. It never logs headers, query strings
// or bodies, so tokens and passwords cannot leak into the log.
func requestLog(logger *zap.Logger) gin.HandlerFunc {
return func(c *gin.Context) {
start := time.Now()
c.Next()
logger.Info("http request",
zap.String("method", c.Request.Method),
zap.String("path", c.Request.URL.Path),
zap.Int("status", c.Writer.Status()),
zap.Duration("latency", time.Since(start)),
)
}
}
// requireAuth accepts only "Authorization: Bearer <jwt>".
func requireAuth(tokens tokenParser) gin.HandlerFunc {
return func(c *gin.Context) {
header := c.GetHeader("Authorization")
token, ok := strings.CutPrefix(header, "Bearer ")
if !ok || token == "" {
writeError(c, http.StatusUnauthorized, "unauthorized", "missing bearer token")
return
}
claims, err := tokens.Parse(token)
if err != nil {
writeError(c, http.StatusUnauthorized, "unauthorized", "invalid or expired token")
return
}
c.Set(ctxUserID, claims.UserID)
c.Set(ctxUsername, claims.Username)
c.Next()
}
}