Files
mtusi2026lab2/internal/auth/auth_test.go
T

80 lines
2.0 KiB
Go

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) *gin.Engine {
e := httpx.NewEngine(slog.New(slog.NewTextHandler(io.Discard, nil)), 1024)
e.GET("/me", auth.RequireUser(users), httpx.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: {}}), 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: {}})
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)
}
}
}