package auth import ( "net/http" "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 { getClaims GetClaimsFunc profileClaims []string } func (h *Handler) serveProfile(w http.ResponseWriter, r *http.Request) { ctx := r.Context() claims, err := h.getClaims(ctx, r, h.profileClaims...) if err != nil { if errors.Is(err, ErrUnauthenticated) { api.ErrorResponse( w, http.StatusUnauthorized, api.ErrCodeUnauthorized, nil, ) return } logger.Error(ctx, "could not retrieve claims", logger.E(errors.WithStack(err))) api.ErrorResponse( w, http.StatusInternalServerError, api.ErrCodeUnknownError, nil, ) return } profile := make(map[string]any) for idx, cl := range h.profileClaims { profile[cl] = claims[idx] } 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, getClaims: opt.GetClaims, } return func(r chi.Router) { r.Get("/api/v1/profile", handler.serveProfile) r.Handle("/auth/*", authHandler) } }