Vue Storefront is now Alokai! Learn More
ChangeCustomerPassword

ChangeCustomerPassword

Implements ChangeCustomerPassword Unified Method.

Source

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

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

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 query(
      api.changeCustomerPassword({
        currentPassword,
        newPassword,
      }),
    );
  } catch (error) {
    if (isInvalidPasswordError(error)) {
      throw context.createHttpError({
        message: "Current password is invalid",
        statusCode: HttpStatusCode.FORBIDDEN,
      });
    }
    throw error;
  }
});

function isInvalidPasswordError(error: unknown): boolean {
  if (!HttpError.isHttpError(error)) {
    return false;
  }

  const graphQLErrors = error.data?.graphQLErrors;
  if (!Array.isArray(graphQLErrors)) {
    return false;
  }

  return graphQLErrors.some(
    (graphQLError) =>
      typeof graphQLError === "object" &&
      graphQLError &&
      "message" in graphQLError &&
      typeof graphQLError.message === "string" &&
      graphQLError.message.includes("Invalid login or password"),
  );
}