Alokai
ReferenceMagentoMethods

LoginCustomer

Implements LoginCustomer Unified Method.

Source

import { getNormalizers } from "@alokai/connect/integration-kit";
import { HttpStatusCode } from "@alokai/connect/middleware";

import { clearStaleCustomerToken, defineApi, query } from "@vsf-enterprise/unified-api-magento";
import type { Customer, GenerateCustomerTokenMutation } from "@vsf-enterprise/unified-api-magento/ecommerceTypes";

const MESSAGE_LOGIN_ERROR = "Could not login customer";

export const loginCustomer = defineApi.loginCustomer(async (context, args) => {
  const { api } = await context.getApiClient();
  const { email, password } = args;
  const { normalizeCustomer } = getNormalizers(context);
  let loginData: GenerateCustomerTokenMutation;
  const tokenCookieName = context.config.cookies.customerCookieName;

  if (context.req.cookies[tokenCookieName]) {
    // An explicit login is intent to re-authenticate: drop any existing
    // (possibly stale) token instead of rejecting with "already logged in", so
    // the stale Bearer token isn't sent on the token mutation. Also expire the
    // response cookie up front, so a failed re-auth can't leave a stale
    // customer cookie wedged on the client. The cookie is re-set below on
    // success (or stays cleared on failure via the catch).
    clearStaleCustomerToken(context);
  }

  try {
    loginData = await query(
      api.generateCustomerToken({
        email,
        password,
        recaptchaToken: "",
      }),
    );
    context.req.cookies[tokenCookieName] = loginData.generateCustomerToken?.token;

    const user = await query(api.customer({}));

    context.res.cookie(
      context.config.cookies.customerCookieName,
      loginData.generateCustomerToken?.token,
    );
    // customer's 'id' field is deprecated in Magento
    return {
      customer: normalizeCustomer(user.customer as Customer),
    };
  } catch {
    context.config.state.setCustomerToken(null);
    throw context.createHttpError({
      message: MESSAGE_LOGIN_ERROR,
      statusCode: HttpStatusCode.UNAUTHORIZED,
    });
  }
});

On this page