All files / src/pages/Login GiveChangePassword.tsx

80.64% Statements 25/31
75.75% Branches 25/33
40% Functions 2/5
79.31% Lines 23/29

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                                                                    1x                     1x 13x 13x 13x 13x 13x   13x                             13x   13x 13x   13x             13x           13x   13x   13x                           13x 12x   11x 2x                           9x                                                                 45x       45x                                                                                                                                                                                      
import { Box, Stack } from "@mui/material";
import { FormProvider } from "react-hook-form";
import {
  CheckCircleIcon,
  InfoIcon,
  MinusCircleIcon,
} from "@phosphor-icons/react";
import qs from "query-string";
import { useLocation, useParams, useSearchParams } from "react-router-dom";
import NiceModal from "@ebay/nice-modal-react";
import { TERMS_OF_SERVICE_MODAL } from "modals/modal_names";
import { useChangePassword } from "hooks/auth-api";
import { useVerifyPasswordResetToken } from "@hooks/auth-api/useVerifyPasswordResetToken";
import LoadingSpinner from "@components/Snipper/LoadingSpinner";
import ExpiredPasswordReset from "@pages/Login/ExpiredPasswordReset";
import GiveLoginOTP from "./GiveLoginOTP";
import { useCustomTheme } from "@theme/hooks/useCustomTheme";
import { showMessage } from "@common/Toast";
import { isValidEmail } from "@validation/regex";
import { PASSWORD_MIN_CHARS } from "@constants/constants";
import { useAppTheme } from "@theme/v2/Provider";
import GiveText from "@shared/Text/GiveText";
import GiveButton from "@shared/Button/GiveButton";
import GivePasswordInput from "@shared/GiveInputs/GivePasswordInput";
import GiveLink from "@shared/Link/GiveLink";
import LoginMainContainer from "./components/LoginMainContainer";
import { getPasswordRequirementState } from "componentsV2/AccountProfile/Security/utils";
import { maskEmail } from "@hooks/auth-api/useLoginOTP";
import { HFCheckbox } from "@shared/HFInputs/HFGiveCheckbox/HFGiveCheckbox";
 
type Props = {
  isToS?: boolean;
};
 
const INDICATIONS = {
  title: "Your password must contain at least:",
  elements: [
    `${PASSWORD_MIN_CHARS} Characters`,
    "One uppercase character",
    "One lowercase character",
    "One number",
    "One special character",
  ],
};
 
const GiveChangePassword = ({ isToS = false }: Props) => {
  const { palette } = useAppTheme();
  const [searchParams] = useSearchParams();
  const { search } = useLocation();
  const { id } = useParams();
  const { isMobileView } = useCustomTheme();
 
  const email = searchParams.get("email") || "";
 
  const {
    methods,
    onSubmit,
    isDisabled,
    alert,
    tmpStep2,
    setTmpStep2,
    handleSubmitFn,
    error2FA,
    handleVerify,
    is2FALoading,
    isLoadingLogin,
    onGoBack,
  } = useChangePassword(isToS);
 
  const { watch, formState, setValue } = methods;
  const values = watch();
 
  const onSuccess = () => {
    const params = qs.parse(search);
    if (isToS && isValidEmail(params?.email as string)) {
      showMessage("Success", "Your account has been successfully validated!");
    }
  };
 
  const { isLoading, isError } = useVerifyPasswordResetToken({
    token: id as string,
    onSuccess,
  });
 
  const isPasswordsMismatch =
    Boolean(values.confirmPassword) &&
    values.confirmPassword !== values.password;
  const isDisabledPassword = !formState.isValid || isPasswordsMismatch;
 
  const openTermsConditions: React.MouseEventHandler<HTMLAnchorElement> = (
    e,
  ) => {
    e.preventDefault();
    NiceModal.show(TERMS_OF_SERVICE_MODAL, {
      agree: () =>
        setValue("termsConditions", true, {
          shouldDirty: true,
          shouldValidate: true,
          shouldTouch: true,
        }),
    });
  };
 
  if (isLoading) return <LoadingSpinner />;
  if (isError) return <ExpiredPasswordReset />;
 
  if (tmpStep2.email) {
    return (
      <GiveLoginOTP
        onSubmit={handleSubmitFn}
        setTmpStep2={setTmpStep2}
        handleVerify={handleVerify}
        onGoBack={onGoBack}
        error={error2FA}
        isLoading={!!is2FALoading || !!isLoadingLogin}
        email={tmpStep2.email}
        isMobileView={isMobileView}
      />
    );
  }
 
  return (
    <LoginMainContainer>
      <Stack gap={"12px"} marginBottom="32px">
        <GiveText variant="h3" sx={{ fontWeight: "300" }}>
          Set New Password
        </GiveText>
        {email ? (
          <GiveText variant="bodyS" color="secondary">
            {maskEmail(email)}
          </GiveText>
        ) : null}
      </Stack>
 
      <FormProvider {...methods}>
        <Box
          component="form"
          onSubmit={methods.handleSubmit(onSubmit)}
          id="change-password"
        >
          <GivePasswordInput
            name="password"
            label="New Password"
            placeholder="New Password"
            hidePlaceholder
            fullWidth
            defaultVisible
          />
          <Stack gap="12px" marginTop="16px" marginBottom="24px">
            <GiveText variant="bodyS" color="secondary">
              {INDICATIONS.title}
            </GiveText>
            <Stack gap="8px">
              {INDICATIONS.elements.map((indication) => {
                const state = getPasswordRequirementState(
                  indication,
                  values.password || "",
                );
                return (
                  <Stack
                    key={indication}
                    direction="row"
                    alignItems="center"
                    gap="8px"
                  >
                    {state === "success" ? (
                      <CheckCircleIcon
                        fill={palette.primitive?.success?.[50]}
                        weight="fill"
                      />
                    ) : (
                      <MinusCircleIcon fill={palette.text.secondary} />
                    )}
                    <GiveText variant="bodyS" color={state}>
                      {indication}
                    </GiveText>
                  </Stack>
                );
              })}
            </Stack>
          </Stack>
          <GivePasswordInput
            name="confirmPassword"
            label="Confirm Password"
            placeholder="Confirm Password"
            hidePlaceholder
            fullWidth
            error={isPasswordsMismatch}
            helper={isPasswordsMismatch ? "Passwords do not match" : undefined}
            defaultVisible
          />
          {isToS ? (
            <Box mt="24px">
              <HFCheckbox
                name="termsConditions"
                label={
                  <Stack direction="row" gap="3px">
                    <GiveText variant="bodyS">I accept the</GiveText>
                    <GiveLink
                      variant="bodyS"
                      component="button"
                      onClick={openTermsConditions}
                      sx={{
                        textDecoration: "underline",
                        textUnderlineOffset: "3px",
                        "& span:before": { display: "none" },
                        "&:hover span:before": { display: "none" },
                      }}
                    >
                      Terms & Conditions
                    </GiveLink>
                  </Stack>
                }
              />
            </Box>
          ) : null}
        </Box>
      </FormProvider>
      {alert && (
        <Stack
          sx={{
            gap: "12px",
            padding: "12px",
            alignItems: "center",
            mt: "24px",
            flexDirection: "row",
            bgcolor: palette.primitive?.transparent["darken-5"],
            borderRadius: "8px",
          }}
        >
          <InfoIcon size={24} />
          <GiveText variant="bodyS">
            New password must not match the previous five used
          </GiveText>
        </Stack>
      )}
      <GiveButton
        label="Continue"
        size="large"
        type="submit"
        form="change-password"
        disabled={isDisabled || isDisabledPassword}
        sx={{ width: "fit-content", ml: "auto", mt: "24px" }}
      />
    </LoginMainContainer>
  );
};
 
export default GiveChangePassword;