package api import ( "net/http" "forge.cadoles.com/wpetit/hydra-webauthn/internal/storage" "github.com/go-chi/chi" "github.com/pkg/errors" "gitlab.com/wpetit/goweb/api" "gitlab.com/wpetit/goweb/logger" "gitlab.com/wpetit/goweb/middleware/container" ) type UpdateUserRequest struct { Username *string `json:"username"` Attributes *map[string]any `json:"attributes"` } type UpdateUserResponse struct { User *storage.User `json:"user"` } func UpdateUser(w http.ResponseWriter, r *http.Request) { userID := chi.URLParam(r, "userID") updateUserReq := &UpdateUserRequest{} if ok := api.Bind(w, r, updateUserReq); !ok { return } ctx := r.Context() ctn := container.Must(ctx) storageSrv := storage.Must(ctn) var ( user *storage.User err error ) if updateUserReq.Username != nil { user, err = storageSrv.User().UpdateUserUsername(ctx, userID, *updateUserReq.Username) if err != nil { if errors.Is(err, storage.ErrNotFound) { logger.Warn(ctx, "could not find user", logger.E(errors.WithStack(err)), logger.F("userID", userID)) api.ErrorResponse(w, http.StatusNotFound, api.ErrCodeNotFound, nil) return } logger.Error(ctx, "could not update username", logger.E(errors.WithStack(err))) api.ErrorResponse(w, http.StatusInternalServerError, api.ErrCodeUnknownError, nil) return } } if updateUserReq.Attributes != nil { user, err = storageSrv.User().UpdateUserAttributes(ctx, userID, *updateUserReq.Attributes) if err != nil { if errors.Is(err, storage.ErrNotFound) { logger.Warn(ctx, "could not find user", logger.E(errors.WithStack(err)), logger.F("userID", userID)) api.ErrorResponse(w, http.StatusNotFound, api.ErrCodeNotFound, nil) return } logger.Error(ctx, "could not update attributes", logger.E(errors.WithStack(err)), logger.F("userID", userID)) api.ErrorResponse(w, http.StatusInternalServerError, api.ErrCodeUnknownError, nil) return } } if user == nil { api.ErrorResponse(w, http.StatusBadRequest, ErrNotModified, nil) return } response := UpdateUserResponse{ User: user, } api.DataResponse(w, http.StatusOK, response) }