Files
breakpilot-lehrer/school-service/internal/middleware/middleware.go
T
Benjamin Admin 306886a42b Phase 8: CSV + ICS export, print view, MkDocs docs, SBOM + dev-mode auth
Auth (Test-Mode):
  - middleware.AuthMiddleware now takes a devMode flag. In dev,
    requests without Authorization fall back to a deterministic dev
    UUID (00000000-...-001) and role=teacher. ENVIRONMENT=production
    re-enables the strict 401 path.
  - main.go wires devMode = cfg.Environment != "production".
  - page.tsx replaces the red 'Anmeldung noch nicht integriert' banner
    with a softer Testumgebung notice; the manual-token form moves
    behind a nested details block.

Export endpoints (school-service):
  - LoadExportLessons joins tt_lesson with tt_period for wall-clock
    times; one query feeds both CSV and ICS.
  - WriteCSV streams 10 columns including pinned flag.
  - WriteICS emits one VEVENT per lesson anchored to a Monday — caller
    overridable via ?start=YYYY-MM-DD. RFC 5545 escapes for ',', ';',
    '\n' in icsEscape().
  - NextMonday helper for the default anchor.
  - GET /timetable/solutions/:id/export.{csv,ics} handlers attach
    Content-Disposition: attachment so browsers download instead of
    rendering.

Frontend:
  - lib/stundenplan/api.ts downloadSolutionExport() fetches as blob,
    triggers a synthetic <a download> click, and forwards the JWT when
    present.
  - PlanView gains CSV / ICS / Drucken buttons next to the perspective
    selector. The toolbar carries class 'no-print' so window.print()
    yields only the grid.
  - globals.css @media print rule hides chrome, forces white
    background, gives the table proper borders for A4.

Docs:
  - docs-src/services/stundenplan/{index,architecture,constraints,
    solver-tuning,export}.md with nav entry in mkdocs.yml under
    Services → Stundenplaner.
  - sbom/stundenplan/README.md lists manually-verified key dependencies
    and the policy reference. scripts/stundenplan-sbom.sh generates
    full machine-readable inventories via go-licenses + pip-licenses
    + license-checker when those tools are available.

Tests:
  - internal/services/timetable_exports_test.go: 4 unit tests covering
    CSV column layout + quoting, ICS structure + DTSTART formatting,
    icsEscape special chars, NextMonday weekday math.
  - studio-v2/e2e/stundenplan-export.spec.ts split out of the main spec
    file (LOC budget) — 3 tests for button render, CSV download,
    ICS download.
  - mockSchoolApi extended with export.csv + export.ics routes.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 08:57:07 +02:00

184 lines
4.4 KiB
Go

package middleware
import (
"net/http"
"strings"
"sync"
"time"
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt/v5"
)
// UserClaims represents the JWT claims structure
type UserClaims struct {
UserID string `json:"user_id"`
Email string `json:"email"`
Role string `json:"role"`
jwt.RegisteredClaims
}
// CORS middleware
func CORS() gin.HandlerFunc {
return func(c *gin.Context) {
origin := c.Request.Header.Get("Origin")
if origin == "" {
origin = "*"
}
c.Writer.Header().Set("Access-Control-Allow-Origin", origin)
c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With")
c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT, DELETE, PATCH")
if c.Request.Method == "OPTIONS" {
c.AbortWithStatus(204)
return
}
c.Next()
}
}
// RequestLogger logs HTTP requests
func RequestLogger() gin.HandlerFunc {
return func(c *gin.Context) {
start := time.Now()
path := c.Request.URL.Path
c.Next()
latency := time.Since(start)
status := c.Writer.Status()
if status >= 400 {
gin.DefaultWriter.Write([]byte(
c.Request.Method + " " + path + " " +
http.StatusText(status) + " " + latency.String() + "\n",
))
}
}
}
// Rate limiter storage
var (
rateLimitMu sync.Mutex
rateLimits = make(map[string][]time.Time)
)
// RateLimiter implements per-IP rate limiting
func RateLimiter() gin.HandlerFunc {
return func(c *gin.Context) {
ip := c.ClientIP()
// Skip rate limiting for internal Docker IPs
if strings.HasPrefix(ip, "172.") || strings.HasPrefix(ip, "10.") || ip == "127.0.0.1" {
c.Next()
return
}
rateLimitMu.Lock()
defer rateLimitMu.Unlock()
now := time.Now()
windowStart := now.Add(-time.Minute)
// Clean old entries
var recent []time.Time
for _, t := range rateLimits[ip] {
if t.After(windowStart) {
recent = append(recent, t)
}
}
// Check limit (500 requests per minute)
if len(recent) >= 500 {
c.AbortWithStatusJSON(http.StatusTooManyRequests, gin.H{
"error": "Rate limit exceeded",
})
return
}
rateLimits[ip] = append(recent, now)
c.Next()
}
}
// devUserID is the deterministic UUID injected when AuthMiddleware runs in
// development mode without a JWT. It's the all-zero UUID's first byte set so
// constraint-ownership filters can still match rows created by the dev user.
const devUserID = "00000000-0000-0000-0000-000000000001"
// AuthMiddleware validates JWT tokens.
//
// devMode=true relaxes the check: requests without an Authorization header
// fall back to a fixed dev user instead of being rejected. Useful for
// studio-v2 against a local school-service when no real login is wired up.
// In production (devMode=false) the original strict behaviour applies.
func AuthMiddleware(jwtSecret string, devMode bool) gin.HandlerFunc {
return func(c *gin.Context) {
authHeader := c.GetHeader("Authorization")
if authHeader == "" {
if devMode {
c.Set("user_id", devUserID)
c.Set("email", "dev@breakpilot.local")
c.Set("role", "teacher")
c.Next()
return
}
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{
"error": "Authorization header required",
})
return
}
tokenString := strings.TrimPrefix(authHeader, "Bearer ")
if tokenString == authHeader {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{
"error": "Invalid authorization format",
})
return
}
token, err := jwt.ParseWithClaims(tokenString, &UserClaims{}, func(token *jwt.Token) (interface{}, error) {
return []byte(jwtSecret), nil
})
if err != nil || !token.Valid {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{
"error": "Invalid or expired token",
})
return
}
claims, ok := token.Claims.(*UserClaims)
if !ok {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{
"error": "Invalid token claims",
})
return
}
// Set user info in context
c.Set("user_id", claims.UserID)
c.Set("email", claims.Email)
c.Set("role", claims.Role)
c.Next()
}
}
// AdminOnly restricts access to admin users
func AdminOnly() gin.HandlerFunc {
return func(c *gin.Context) {
role := c.GetString("role")
if role != "admin" && role != "super_admin" {
c.AbortWithStatusJSON(http.StatusForbidden, gin.H{
"error": "Admin access required",
})
return
}
c.Next()
}
}