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 { defineApi, getCurrentCustomer } from "@vsf-enterprise/unified-api-commercetools";

const isUnauthorizedError = (error: unknown) => {
  // Check if it's an HttpError from the Apollo adapter
  if (!HttpError.isHttpError(error)) {
    return false;
  }

  // Apollo error adapter stores GraphQL errors in error.data.graphQLErrors
  const graphQLErrors = error.data?.graphQLErrors as
    | { extensions?: { code?: string } }[]
    | undefined;

  return graphQLErrors?.[0]?.extensions?.code === "InvalidCurrentPassword";
};

export const changeCustomerPassword = defineApi.changeCustomerPassword(async (context, args) => {
  const { version } = await getCurrentCustomer(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 {
    const { api } = await context.getApiClient();
    await api.customerChangeMyPassword(version, currentPassword, newPassword);
  } catch (error) {
    if (isUnauthorizedError(error)) {
      throw context.createHttpError({
        cause: error,
        message: "Password change failed",
        statusCode: HttpStatusCode.FORBIDDEN,
      });
    }
    throw error;
  }
});