Перенести WithUser в httpx

This commit is contained in:
2026-10-06 14:49:19 +03:00
parent f42bf97b3a
commit 6720108793
6 changed files with 60 additions and 48 deletions
-18
View File
@@ -5,7 +5,6 @@ package auth
import (
"context"
"errors"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
@@ -46,20 +45,3 @@ func RequireUser(users UserLookup) gin.HandlerFunc {
c.Next()
}
}
// UserHandler is a handler that needs the identified caller.
type UserHandler func(c *gin.Context, actor uuid.UUID)
// WithUser adapts a UserHandler to gin. Reaching it without RequireUser in
// front is a wiring mistake, so it is reported as an internal error rather
// than blamed on the client with a 401.
func WithUser(h UserHandler) gin.HandlerFunc {
return func(c *gin.Context) {
actor, ok := httpx.UserID(c)
if !ok {
httpx.Error(c, errors.New("route is missing the RequireUser middleware"))
return
}
h(c, actor)
}
}
+4 -16
View File
@@ -28,13 +28,9 @@ func echoActor(c *gin.Context, actor uuid.UUID) {
httpx.JSON(c, http.StatusOK, map[string]string{"id": actor.String()})
}
func newEngine(users lookup, guarded bool) *gin.Engine {
func newEngine(users lookup) *gin.Engine {
e := httpx.NewEngine(slog.New(slog.NewTextHandler(io.Discard, nil)), 1024)
if guarded {
e.GET("/me", auth.RequireUser(users), auth.WithUser(echoActor))
} else {
e.GET("/me", auth.WithUser(echoActor))
}
e.GET("/me", auth.RequireUser(users), httpx.WithUser(echoActor))
return e
}
@@ -60,7 +56,7 @@ func call(e *gin.Engine, header string) (*httptest.ResponseRecorder, string) {
func TestKnownUserReachesHandlerWithItsID(t *testing.T) {
alice := ident.New()
rec, got := call(newEngine(lookup{alice: {}}, true), alice.String())
rec, got := call(newEngine(lookup{alice: {}}), alice.String())
if rec.Code != http.StatusOK || got != alice.String() {
t.Fatalf("status %d, handler saw %q, want %s", rec.Code, got, alice)
}
@@ -68,7 +64,7 @@ func TestKnownUserReachesHandlerWithItsID(t *testing.T) {
func TestMiddlewareRejectsMissingMalformedAndUnknownWith401(t *testing.T) {
alice := ident.New()
e := newEngine(lookup{alice: {}}, true)
e := newEngine(lookup{alice: {}})
for name, header := range map[string]string{
"missing": "",
"malformed": "not-a-uuid",
@@ -81,11 +77,3 @@ func TestMiddlewareRejectsMissingMalformedAndUnknownWith401(t *testing.T) {
}
}
}
func TestWithUserWithoutMiddlewareIsAWiringError(t *testing.T) {
alice := ident.New()
rec, code := call(newEngine(lookup{alice: {}}, false), alice.String())
if rec.Code != http.StatusInternalServerError || code != "internal_error" {
t.Fatalf("status = %d code = %q, want 500 internal_error", rec.Code, code)
}
}