package middleware import ( "context" "net/http" "time" "ibd-trader/internal/database" ) const SessionCookie = "_session" func Auth(store database.SessionStore) func(next http.Handler) http.Handler { return func(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // Get session cookie cookie, err := r.Cookie(SessionCookie) if err != nil { http.Error(w, "Unauthorized", http.StatusUnauthorized) return } // Check session session, err := store.GetSession(r.Context(), cookie.Value) if err != nil { http.Error(w, "Error getting session", http.StatusInternalServerError) return } if session == nil { http.Error(w, "Unauthorized", http.StatusUnauthorized) return } // Check session expiry if session.OAuthToken.Expiry.Before(time.Now()) { http.Error(w, "Session expired", http.StatusUnauthorized) return } // Add session to context ctx := context.WithValue(r.Context(), "session", session) next.ServeHTTP(w, r.WithContext(ctx)) }) } }