package auth import ( "net/http" "forge.cadoles.com/arcad/edge/pkg/jwtutil" "github.com/go-chi/chi/v5" "github.com/pkg/errors" "gitlab.com/wpetit/goweb/api" "gitlab.com/wpetit/goweb/logger" ) type MountFunc func(r chi.Router) type Handler struct { getClaim GetClaimFunc profileClaims []string } func (h *Handler) serveProfile(w http.ResponseWriter, r *http.Request) { ctx := r.Context() profile := make(map[string]any) for _, name := range h.profileClaims { value, err := h.getClaim(ctx, r, name) if err != nil { if errors.Is(err, jwtutil.ErrUnauthenticated) { api.ErrorResponse( w, http.StatusUnauthorized, api.ErrCodeUnauthorized, nil, ) return } logger.Error(ctx, "could not retrieve claims", logger.CapturedE(errors.WithStack(err))) api.ErrorResponse( w, http.StatusInternalServerError, api.ErrCodeUnknownError, nil, ) return } profile[name] = value } api.DataResponse(w, http.StatusOK, struct { Profile map[string]any `json:"profile"` }{ Profile: profile, }) } func Mount(authHandler http.Handler, funcs ...OptionFunc) MountFunc { opt := defaultOptions() for _, fn := range funcs { fn(opt) } handler := &Handler{ profileClaims: opt.ProfileClaims, getClaim: opt.GetClaim, } return func(r chi.Router) { r.Get("/api/v1/profile", handler.serveProfile) r.Handle("/auth/*", authHandler) } }