Vue Storefront is now Alokai! Learn More
LoginCustomer

LoginCustomer

Implements LoginCustomer Unified Method.

Source

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

const MESSAGE_LOGIN_ERROR = "Could not login customer";
const MESSAGE_ALREADY_LOGGED_IN = "Customer is already logged in";

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

  if (context.req.cookies[tokenCookieName]) {
    throw { statusCode: 403, message: MESSAGE_ALREADY_LOGGED_IN };
  }

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

    const user = await query(context.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 (error) {
    console.error(error);
    context.config.state.setCustomerToken(null);
    throw { statusCode: 401, message: MESSAGE_LOGIN_ERROR };
  }
});