Перенести решение лабораторной 1 как основу для лабораторной 2

This commit is contained in:
2026-10-06 11:54:05 +03:00
parent 65003b6119
commit 5c3f2bfad0
54 changed files with 4472 additions and 0 deletions
+65
View File
@@ -0,0 +1,65 @@
// Package auth identifies the caller. In this lab the identity is the
// X-User-Id header naming a registered user: identification, not
// authentication, by design of the assignment.
package auth
import (
"context"
"errors"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"messenger/internal/platform/apperr"
"messenger/internal/platform/httpx"
"messenger/internal/platform/ident"
)
type UserLookup interface {
Exists(ctx context.Context, id uuid.UUID) (bool, error)
}
// RequireUser answers 401 unless X-User-Id names a registered user, and
// records that user for the handlers behind it.
func RequireUser(users UserLookup) gin.HandlerFunc {
return func(c *gin.Context) {
raw := c.GetHeader("X-User-Id")
if raw == "" {
httpx.Error(c, apperr.Unauthorized("X-User-Id header is required"))
return
}
id, err := ident.Parse(raw)
if err != nil {
httpx.Error(c, apperr.Unauthorized("X-User-Id must be the UUID of a registered user"))
return
}
ok, err := users.Exists(c.Request.Context(), id)
if err != nil {
httpx.Error(c, err)
return
}
if !ok {
httpx.Error(c, apperr.Unauthorized("X-User-Id must be the UUID of a registered user"))
return
}
httpx.SetUserID(c, id)
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)
}
}
+91
View File
@@ -0,0 +1,91 @@
package auth_test
import (
"context"
"encoding/json"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"testing"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"messenger/internal/auth"
"messenger/internal/platform/httpx"
"messenger/internal/platform/ident"
)
type lookup map[uuid.UUID]struct{}
func (l lookup) Exists(_ context.Context, id uuid.UUID) (bool, error) {
_, ok := l[id]
return ok, nil
}
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 {
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))
}
return e
}
func call(e *gin.Engine, header string) (*httptest.ResponseRecorder, string) {
req := httptest.NewRequest(http.MethodGet, "/me", nil)
if header != "" {
req.Header.Set("X-User-Id", header)
}
rec := httptest.NewRecorder()
e.ServeHTTP(rec, req)
var body struct {
ID string `json:"id"`
Error struct {
Code string `json:"code"`
} `json:"error"`
}
_ = json.Unmarshal(rec.Body.Bytes(), &body)
if body.ID != "" {
return rec, body.ID
}
return rec, body.Error.Code
}
func TestKnownUserReachesHandlerWithItsID(t *testing.T) {
alice := ident.New()
rec, got := call(newEngine(lookup{alice: {}}, true), alice.String())
if rec.Code != http.StatusOK || got != alice.String() {
t.Fatalf("status %d, handler saw %q, want %s", rec.Code, got, alice)
}
}
func TestMiddlewareRejectsMissingMalformedAndUnknownWith401(t *testing.T) {
alice := ident.New()
e := newEngine(lookup{alice: {}}, true)
for name, header := range map[string]string{
"missing": "",
"malformed": "not-a-uuid",
"braces": "{" + alice.String() + "}",
"unknown": ident.New().String(),
} {
rec, code := call(e, header)
if rec.Code != http.StatusUnauthorized || code != "unauthorized" {
t.Errorf("%s: status = %d code = %q, want 401 unauthorized", name, rec.Code, code)
}
}
}
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)
}
}