Перенести 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)
}
}
+6 -7
View File
@@ -6,7 +6,6 @@ import (
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"messenger/internal/auth"
"messenger/internal/platform/apperr"
"messenger/internal/platform/httpx"
"messenger/internal/platform/ident"
@@ -21,13 +20,13 @@ func NewHandler(chats *Service) *Handler {
return &Handler{chats: chats}
}
// Register mounts the chat endpoints on a router guarded by RequireUser.
// Register mounts the chat endpoints on a router guarded by the authentication middleware.
func (h *Handler) Register(protected gin.IRouter) {
protected.POST("/chats", auth.WithUser(h.create))
protected.GET("/chats", auth.WithUser(h.list))
protected.GET("/chats/:chat_id", auth.WithUser(h.get))
protected.POST("/chats/:chat_id/messages", auth.WithUser(h.send))
protected.GET("/chats/:chat_id/messages", auth.WithUser(h.history))
protected.POST("/chats", httpx.WithUser(h.create))
protected.GET("/chats", httpx.WithUser(h.list))
protected.GET("/chats/:chat_id", httpx.WithUser(h.get))
protected.POST("/chats/:chat_id/messages", httpx.WithUser(h.send))
protected.GET("/chats/:chat_id/messages", httpx.WithUser(h.history))
}
type createChatRequest struct {
+25
View File
@@ -282,6 +282,31 @@ func TestUserIDRoundTripAndAccessLogAttribution(t *testing.T) {
}
}
func TestWithUserPassesTheIdentifiedCaller(t *testing.T) {
actor := uuid.MustParse("22222222-2222-4222-8222-222222222222")
e := newEngine(t, nil)
e.GET("/actor",
func(c *gin.Context) { httpx.SetUserID(c, actor) },
httpx.WithUser(func(c *gin.Context, got uuid.UUID) {
httpx.JSON(c, http.StatusOK, gin.H{"id": got.String()})
}))
rec, _ := do(t, e, http.MethodGet, "/actor", "", nil)
if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), actor.String()) {
t.Fatalf("handler did not receive the caller: %d %s", rec.Code, rec.Body.String())
}
}
// Reaching WithUser without an authentication middleware in front is a
// wiring mistake, so it must not be blamed on the client with a 401.
func TestWithUserWithoutIdentityIsAWiringError(t *testing.T) {
e := newEngine(t, nil)
e.GET("/actor", httpx.WithUser(func(c *gin.Context, _ uuid.UUID) {
httpx.JSON(c, http.StatusOK, gin.H{})
}))
rec, eb := do(t, e, http.MethodGet, "/actor", "", nil)
assertError(t, rec, eb, http.StatusInternalServerError, "internal_error")
}
func logEntry(t *testing.T, logs *bytes.Buffer) map[string]any {
t.Helper()
var entry map[string]any
+23 -4
View File
@@ -1,16 +1,18 @@
package httpx
import (
"errors"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
)
const keyUserID = "messenger.user_id"
// SetUserID records the identified caller for the handlers behind the
// identification middleware and for the access log. It lives here rather
// than in the auth package because the access log needs it and auth already
// depends on this package.
// SetUserID records the authenticated caller for the handlers behind the
// authentication middleware and for the access log. It lives here rather
// than in the auth package because the access log needs it and the business
// modules must not depend on auth.
func SetUserID(c *gin.Context, id uuid.UUID) {
c.Set(keyUserID, id)
}
@@ -23,3 +25,20 @@ func UserID(c *gin.Context) (uuid.UUID, bool) {
id, ok := v.(uuid.UUID)
return id, ok
}
// UserHandler is a handler that needs the authenticated caller.
type UserHandler func(c *gin.Context, actor uuid.UUID)
// WithUser adapts a UserHandler to gin. Reaching it without the
// authentication middleware 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 := UserID(c)
if !ok {
Error(c, errors.New("route is missing the authentication middleware"))
return
}
h(c, actor)
}
}
+2 -3
View File
@@ -6,7 +6,6 @@ import (
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"messenger/internal/auth"
"messenger/internal/platform/httpx"
)
@@ -19,10 +18,10 @@ func NewHandler(users *Service) *Handler {
}
// Register mounts registration on the public router and the current-user
// endpoint on the router guarded by RequireUser.
// endpoint on the router guarded by the authentication middleware.
func (h *Handler) Register(public, protected gin.IRouter) {
public.POST("/users", h.register)
protected.GET("/users/me", auth.WithUser(h.me))
protected.GET("/users/me", httpx.WithUser(h.me))
}
type createRequest struct {