All files / src/hooks/auth-api useHandleLogin.ts

49.52% Statements 52/105
29.85% Branches 20/67
66.66% Functions 10/15
50.48% Lines 52/103

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332                                                      28x 28x     28x 28x               28x 28x 28x 28x 28x 28x 28x 28x 28x 3x               28x             2x       2x 2x                                                                                                   28x                               28x 3x               3x   1x 1x             1x     3x     2x                         2x                             2x         2x                                 2x 4x     2x 2x             2x 6x     2x                             2x 2x                             2x 2x       2x                     2x                 2x         2x               28x       28x       28x                                             36x 2x 2x 2x    
import { TAccounts } from "@customTypes/accounts.types";
import NiceModal from "@ebay/nice-modal-react";
import { useFingerprint } from "@hooks/common/useFingerprint";
import { useSessionTimeoutWithWorker } from "@hooks/useSessionTimeoutWithWorker";
import { useAppDispatch } from "@redux/hooks";
import { setSelectedAccount } from "@redux/slices/auth/accounts";
import { login, updatePartialUser } from "@redux/slices/auth/auth";
import { Role, TAuthUser } from "@redux/slices/auth/types";
import { customInstance } from "@services/api";
import { usePutAccount } from "@services/api/onboarding/user";
import { getGivecashToWebData } from "@utils/queryString";
import addDays from "date-fns/addDays";
import { PLATFORM_TIMEZONE } from "@utils/timezones";
import Cookies from "js-cookie";
import {
  GIVE_ACCOUNT_SELECTION_MODAL,
  GIVE_NO_ACCOUNT_MODAL,
  GIVE_PASSWORD_EXPIRED_MODAL,
} from "modals/modal_names";
import React, { useRef, useState } from "react";
import { useMutation } from "react-query";
import { useNavigate } from "react-router-dom";
import { LoginConfigs } from "./types";
import { useLoginOTP } from "./useLoginOTP";
import { withRecaptchaToken } from "@utils/getRecaptchaToken";
 
export default function useHandleLogin({ email }: { email: string }) {
  const navigate = useNavigate();
  const [tmpStep2, setTmpStep2] = React.useState<{ email: string }>({
    email: "",
  });
  const hasResentOnceRef = React.useRef<boolean>(false);
  const [isDifferentAccount, setIsDifferentAccount] = React.useState(false);
  const {
    handleVerify,
    error: error2FA,
    isLoading: is2FALoading,
    loginRef,
    resendCode,
    setError,
  } = useLoginOTP();
  const { setSessionStartTime } = useSessionTimeoutWithWorker();
  const { fingerprint } = useFingerprint();
  const { mutate } = usePutAccount();
  const loginConfigs = useRef<LoginConfigs>();
  const dispatch = useAppDispatch();
  const [showAlert, setShowAlert] = useState("");
  const [isEmailSent, setIsEmailSent] = useState(false);
  const signinMutation = useMutation((data: any) => {
    return customInstance({
      url: "/signin",
      method: "POST",
      withCredentials: true,
      data,
    });
  });
 
  const handleLogin = ({
    accounts,
    user,
    userId,
    preSelectedAccount,
    nextRoute,
  }: LoginConfigs) => {
    const redirectParam = new URLSearchParams(window.location.search).get(
      "redirect",
    );
 
    if (accounts?.length > 1) {
      NiceModal.show(GIVE_ACCOUNT_SELECTION_MODAL, {
        userAccID: userId,
        preSelectedAccount,
      });
    } else Eif (accounts?.length === 1) {
      const merchant = {
        id: accounts[0].id,
        userAccID: accounts[0].userAccID,
        userRole: accounts[0].userRole,
        name: accounts[0].name,
        userEmail: user.email,
        merchType: accounts[0].merchType,
        img: accounts[0].avatarURL,
      };
      const updatedUser = {
        ...user,
        id: merchant.id,
        name: merchant.name,
      };
 
      dispatch(setSelectedAccount(merchant));
      mutate(merchant.id);
      Cookies.set("user", JSON.stringify(updatedUser), { expires: 1 });
      setSessionStartTime();
      dispatch(login(updatedUser));
      // if coming from mobile and has redirect route
      if (redirectParam) {
        navigate(redirectParam);
      } else {
        nextRoute ? navigate(nextRoute) : navigate(`/${user.role}`);
      }
    } else {
      Cookies.set("user", JSON.stringify(user), { expires: 1 });
      dispatch(login(user));
 
      if (redirectParam) {
        navigate(redirectParam);
      } else {
        navigate(`/${user.role}`);
      }
    }
  };
 
  // GB20910: handleResendResult is called both for the initial OTP send (when
  // needsTFA=true after /signin) and for subsequent resend attempts triggered
  // by the user. Previously, the guard `if (hasResentOnceRef.current)` meant
  // the first call — i.e. the initial send — never surfaced errors to the user.
  // If POST /tfa-verifications failed (e.g. Mailchimp down), the user would
  // land on the OTP screen with no code and no feedback. The `else if` branch
  // ensures a failure on the initial send is shown immediately.
  const handleResendResult = (type: "success" | "error") => {
    if (hasResentOnceRef.current) {
      // Subsequent calls: shown after a CAPTCHA-triggered resend
      const message =
        type === "success"
          ? "CAPTCHA verification was unsuccessful. A new OTP code has been issued to you, please try again."
          : "CAPTCHA verification was unsuccessful. Failed to resend the OTP code. Please try again.";
      setError(message);
    } else if (type === "error") {
      // GB20910: First call (initial send on needsTFA). Surface the failure so
      // the user knows the code was not delivered and can act accordingly.
      setError("Failed to send the verification code. Please try again.");
    }
    hasResentOnceRef.current = true;
  };
 
  const onHandleSubmit = (data: any) => {
    const customData = {
      email: data.email,
      password: data.password,
      hasAcceptedTC: data.hasAcceptedTC,
      captchaToken: data.captchaToken,
      fingerprintToken: fingerprint,
    };
 
    signinMutation.mutate(customData, {
      onError: (error: any) => {
        const errorMessage = error?.response?.data?.message;
        Iif (errorMessage === "The provided password has expired.") {
          NiceModal.show(GIVE_PASSWORD_EXPIRED_MODAL, {
            email: data.email,
            setIsEmailSent,
          });
          return;
        }
        setShowAlert("Incorrect Email or Password");
      },
      onSettled() {
        data?.onFinally?.();
      },
      onSuccess: async (res: any) => {
        Iif (res.needsTFA) {
          loginRef.current = {
            password: data.password,
            remember: data.remember,
            email: data.email,
            termsConditions: data.termsConditions,
          };
          resendCode("email", {
            onError: () => handleResendResult("error"),
            onSuccess: () => handleResendResult("success"),
          });
          return setTmpStep2({ email: email });
        }
        Iif (
          res.user?.passwordLastChangedAt &&
          addDays(new Date(res.user.passwordLastChangedAt * 1000), 90) <
            new Date()
        ) {
          NiceModal.show(GIVE_PASSWORD_EXPIRED_MODAL, {
            email: data.email,
            setIsEmailSent,
          });
          return;
        }
 
        //REFACTOR: BE is not returning the correct value on signin, it always returns the previously used 'accessAccMerchType'
        //this is a fix that we only need when there's one account, otherwise the user is asked to choose
        //fix should be handled on BE on long-term
        const role = getUserRole(
          res.accounts?.length === 1
            ? res.accounts[0].merchType
            : res.accessAccMerchType,
        );
        const user: TAuthUser = {
          id: res.user.accID,
          name: res.user.firstName,
          email: res.user.email,
          userAccID: res.user.accID,
          role: role,
          img: res.user.imageURL,
          globalName: {
            firstName: res.user.firstName,
            lastName: res.user.lastName,
            phoneNumber: res.user.phoneNumber,
          },
          currency: res?.user.currency,
          language: res?.user.language,
          timezone: PLATFORM_TIMEZONE.toLowerCase(),
        };
 
        const hasAnyBusinessAcc = res?.accounts?.some(
          (acc: any) => acc.type === "merchant",
        );
 
        if (res.accessAccType === "merchant" || hasAnyBusinessAcc) {
          dispatch(
            updatePartialUser({
              userAccID: user.userAccID,
              globalName: user.globalName,
              img: res.user.imageURL,
            }),
          );
          const users: TAccounts<"merchant">[] = (res?.accounts || []).filter(
            (item: any) => item.type !== "user",
          ) as any;
 
          Iif (users.length === 0) {
            // If user did 2FA and has no active organizations, we need to redirect them to login page to show error
            if (tmpStep2.email) {
              setTmpStep2({ email: "" });
            }
            setShowAlert("You currently have no active organization.");
            return;
          }
          let preSelectedAccount;
          const {
            acquirerId,
            enterpriseId,
            merchantId,
            fromMobile,
            merchantName,
          } = getGivecashToWebData();
          Iif (fromMobile) {
            let acquirer, enterprise, merchant;
            for (const acc of users || []) {
              if (acc.id === acquirerId) {
                acquirer = acc;
              }
              if (acc.id === enterpriseId) {
                enterprise = acc;
              }
              if (acc.id === merchantId) {
                merchant = acc;
              }
            }
            preSelectedAccount = acquirer || enterprise || merchant;
          }
          let nextRoute = "";
          Iif (preSelectedAccount?.merchType === "submerchant") {
            nextRoute = `/merchant/manage-money`;
          }
 
          Iif (
            preSelectedAccount?.merchType &&
            ["enterprise", "acquirer"].includes(preSelectedAccount?.merchType)
          ) {
            nextRoute = `/${
              preSelectedAccount.merchType === "enterprise"
                ? "provider"
                : preSelectedAccount.merchType
            }/manage-money?merchantName=${encodeURIComponent(merchantName)}`;
          }
 
          const handleLoginArgs: LoginConfigs = {
            accounts: users,
            userId: res.user.accID,
            user,
            nextRoute,
            preSelectedAccount,
          };
 
          // if selected merchant doesnt belong to the credentials entered
          Iif (fromMobile && !nextRoute) {
            setIsDifferentAccount(true);
            loginConfigs.current = handleLoginArgs;
            return;
          }
          handleLogin(handleLoginArgs);
        } else E{
          NiceModal.show(GIVE_NO_ACCOUNT_MODAL);
        }
      },
    });
  };
 
  const onGoBack = () => {
    hasResentOnceRef.current = false;
  };
 
  const getRecaptchaToken = (onLogin: (token: string) => void) => {
    withRecaptchaToken("login", onLogin);
  };
 
  return {
    isLoading: signinMutation.isLoading,
    onHandleSubmit,
    showAlert,
    setShowAlert,
    loginRef,
    resendCode,
    error2FA,
    is2FALoading,
    handleVerify,
    tmpStep2,
    setTmpStep2,
    isDifferentAccount,
    setIsDifferentAccount,
    loginConfigs,
    handleLogin,
    onGoBack,
    getRecaptchaToken,
    signinMutationIsLoading: signinMutation.isLoading,
    isEmailSent, //check if email was sent on expired password reset
  };
}
 
const getUserRole = (role: string) => {
  Iif (role === "submerchant") return "merchant";
  Iif (role === "enterprise") return "provider";
  return (role || "merchant") as Role;
};