Vue Storefront is now Alokai! Learn More
ChangeCustomerPassword

ChangeCustomerPassword

Implements ChangeCustomerPassword Unified Method.

Source

import "./extended";
import { validatePassword } from "@alokai/connect/integration-kit";
import { HttpError, HttpStatusCode } from "@alokai/connect/middleware";

import { assertAuthorized, defineApi } from "@vsf-enterprise/unified-api-sapcc";

const isUnauthorizedError = (error: unknown): error is HttpError => {
  if (!HttpError.isHttpError(error)) return false;

  const axiosError = error.cause;

  return !!(
    axiosError &&
    typeof axiosError === "object" &&
    "response" in axiosError &&
    (axiosError as { response?: { data?: { errors?: { type?: string }[] } } }).response?.data
      ?.errors?.[0]?.type === "PasswordMismatchError"
  );
};

export const changeCustomerPassword = defineApi.changeCustomerPassword(async (context, args) => {
  const { api } = await context.getApiClient();
  await assertAuthorized(context);

  const { confirmPassword, currentPassword, newPassword } = args;

  if (!validatePassword(newPassword, confirmPassword)) {
    throw context.createHttpError({
      message: "Password does not meet the requirements",
      statusCode: HttpStatusCode.UNPROCESSABLE_ENTITY,
    });
  }

  try {
    await api.replaceUserPassword({
      _new: newPassword,
      old: currentPassword,
    });
  } catch (error) {
    if (isUnauthorizedError(error)) {
      throw error.withStatusCode(403, "Password change failed");
    }
    throw error;
  }
});