package middleware import ( "context" "errors" "html/template" "log/slog" "net/http" "net/url" "git.leonardobishop.net/instancer/pkg/auth" "git.leonardobishop.net/instancer/pkg/session" ) func MustAuthenticate(tmpl *template.Template, store *session.MemoryStore, authProvider *auth.OIDCAuthProvider) func(http.HandlerFunc) http.HandlerFunc { return func(next http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { sessionCookie, err := r.Cookie("instancer-session") if err != nil { http.Redirect(w, r, "/auth", http.StatusFound) return } s := store.GetByToken(sessionCookie.Value) if s == nil { http.Redirect(w, r, "/auth?error="+url.QueryEscape("Session does not exist"), http.StatusFound) return } err = authProvider.UpdateUserInfo(r.Context(), s) if err != nil { if errors.Is(err, auth.ErrInvalidToken) { http.Redirect(w, r, "/auth?error="+url.QueryEscape("OIDC authentication has expired"), http.StatusFound) return } slog.Error("error updating user info", "cause", err) w.Header().Add("HX-Redirect", "/problem") tmpl.ExecuteTemplate(w, "problem.html", struct { Error string ShowLogout bool }{ Error: "There was a problem fetching your user info. Try again later.", ShowLogout: true, }) return } if s.TeamID == "" || s.TeamName == "" { w.Header().Add("HX-Redirect", "/problem") tmpl.ExecuteTemplate(w, "problem.html", struct { Error string ShowLogout bool }{ Error: "You are not part of a team. Please join a team and then refresh this page.", ShowLogout: true, }) return } ctx := context.WithValue(r.Context(), "session", s) next(w, r.WithContext(ctx)) } } }