~sircmpwn/core-go

23808bb0998277ff986660ce21c97b2dc88139a9 — Simon Ser 5 months ago d99f098
auth: add RequireMiddleware

Same as Middleware, but requires auth for all requests. Will be
useful to drop hacks from pages.sr.ht.
1 files changed, 11 insertions(+), 9 deletions(-)

M auth/middleware.go
M auth/middleware.go => auth/middleware.go +11 -9
@@ 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 {