59 lines
2 KiB
Go
59 lines
2 KiB
Go
// Dieses File enthält die Middleware die eine Web-Session prüft — das eigentliche
|
|
// Signieren/Verifizieren steckt in handler.SignSession/handler.VerifySession
|
|
// (dort auch von den Login-Handlern genutzt).
|
|
package middleware
|
|
|
|
import (
|
|
"net/http"
|
|
"strings"
|
|
|
|
"wiki/handler"
|
|
)
|
|
|
|
// RequireTeamSession ist die Middleware für die Web-Ansicht ("/" und "/search").
|
|
// Ohne gültigen Session-Cookie wird auf /login umgeleitet. Mit gültigem Cookie
|
|
// wird das aufgelöste Team (bzw. der Admin-Status) im Request-Context abgelegt —
|
|
// siehe handler.WithTeam / handler.TeamFromContext.
|
|
func RequireTeamSession(next http.Handler, registry *handler.TeamRegistry, secret []byte) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
cookie, err := r.Cookie(handler.SessionCookieName)
|
|
if err != nil {
|
|
http.Redirect(w, r, "/login", http.StatusSeeOther)
|
|
return
|
|
}
|
|
|
|
subject, ok := handler.VerifySession(cookie.Value, secret)
|
|
if !ok {
|
|
http.Redirect(w, r, "/login", http.StatusSeeOther)
|
|
return
|
|
}
|
|
|
|
switch {
|
|
case subject == "admin":
|
|
next.ServeHTTP(w, r.WithContext(handler.WithTeam(r.Context(), nil, true)))
|
|
|
|
case strings.HasPrefix(subject, "admin:"):
|
|
teamID := strings.TrimPrefix(subject, "admin:")
|
|
team, ok := registry.ByID(teamID)
|
|
if !ok {
|
|
// Team wurde inzwischen entfernt — Admin sieht wieder die Übersicht.
|
|
next.ServeHTTP(w, r.WithContext(handler.WithTeam(r.Context(), nil, true)))
|
|
return
|
|
}
|
|
next.ServeHTTP(w, r.WithContext(handler.WithTeam(r.Context(), team, true)))
|
|
|
|
case strings.HasPrefix(subject, "team:"):
|
|
teamID := strings.TrimPrefix(subject, "team:")
|
|
team, ok := registry.ByID(teamID)
|
|
if !ok {
|
|
// Team wurde inzwischen entfernt (z.B. aus teams.yaml gelöscht) — neu einloggen lassen.
|
|
http.Redirect(w, r, "/login", http.StatusSeeOther)
|
|
return
|
|
}
|
|
next.ServeHTTP(w, r.WithContext(handler.WithTeam(r.Context(), team, false)))
|
|
|
|
default:
|
|
http.Redirect(w, r, "/login", http.StatusSeeOther)
|
|
}
|
|
})
|
|
}
|