// 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" "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() } }