From 23808bb0998277ff986660ce21c97b2dc88139a9 Mon Sep 17 00:00:00 2001 From: Simon Ser Date: Mon, 22 Jan 2024 21:41:29 +0000 Subject: [PATCH] auth: add RequireMiddleware Same as Middleware, but requires auth for all requests. Will be useful to drop hacks from pages.sr.ht. --- auth/middleware.go | 20 +++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/auth/middleware.go b/auth/middleware.go index ec92f1e8487e65bc834f40e0c7eb4b7c18ba5ee8..03321ee2cb1f484d8a59c9efa6c1e0d2fc279ed1 100644 --- a/auth/middleware.go +++ b/auth/middleware.go @@ -17,6 +17,7 @@ import ( "sync/atomic" "time" + chimiddleware "github.com/go-chi/chi/v5/middleware" "github.com/vaughan0/go-ini" "github.com/vektah/gqlparser/v2/gqlerror" @@ -688,7 +689,7 @@ func WebhookAuth(ctx context.Context, auth *AuthContext, return context.WithValue(ctx, userCtxKey, &whAuth), nil } -func Middleware(conf ini.File, apiconf string) func(http.Handler) http.Handler { +func RequireMiddleware(conf ini.File, apiconf string) func(http.Handler) http.Handler { var internalNet []*net.IPNet src, ok := conf.Get(apiconf, "internal-ipnet") if !ok { @@ -705,14 +706,6 @@ func Middleware(conf ini.File, apiconf string) func(http.Handler) http.Handler { return func(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if !strings.HasPrefix(r.URL.Path, "/query") || - r.URL.Path == "/query/metrics" || - r.URL.Path == "/query/api-meta.json" || - strings.HasPrefix(r.URL.Path, "/query/external/") { - next.ServeHTTP(w, r) - return - } - cookie, err := r.Cookie("sr.ht.unified-login.v1") if err == nil { cookieAuth(cookie, w, r, next) @@ -761,6 +754,15 @@ func Middleware(conf ini.File, apiconf string) func(http.Handler) http.Handler { } } +func Middleware(conf ini.File, apiconf string) func(http.Handler) http.Handler { + return chimiddleware.Maybe(RequireMiddleware(conf, apiconf), func(r *http.Request) bool { + return strings.HasPrefix(r.URL.Path, "/query") && + r.URL.Path != "/query/metrics" && + r.URL.Path != "/query/api-meta.json" && + !strings.HasPrefix(r.URL.Path, "/query/external/") + }) +} + func ForContext(ctx context.Context) *AuthContext { raw, ok := ctx.Value(userCtxKey).(*AuthContext) if !ok {