Files
mtusi2026lab2/internal/platform/httpx/identity.go
T

45 lines
1.1 KiB
Go

package httpx
import (
"errors"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
)
const keyUserID = "messenger.user_id"
// 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)
}
func UserID(c *gin.Context) (uuid.UUID, bool) {
v, ok := c.Get(keyUserID)
if !ok {
return uuid.Nil, false
}
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)
}
}