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