All files / src/components/ProfileMenu/modals/Tabs/SecurityTab ResetPassword.tsx

90.9% Statements 30/33
85.41% Branches 41/48
80% Functions 8/10
93.75% Lines 30/32

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                                              7x 384x 384x 384x   384x 96x     96x             384x         384x 60x     384x 384x 384x   384x 60x     384x                                                                                                           384x                 384x                             1152x                   1920x                                               7x             1152x                         7x                                             7x 900x   180x       180x       180x       180x       180x                  
import { InputEyeIcon, InputEyeIconNotVisible } from "@assets/icons";
import { RHFInput } from "@common/Input";
import { Text } from "@common/Text";
import { PASSWORD_MIN_CHARS } from "@constants/constants";
import { Box, Divider, InputAdornment, Stack } from "@mui/material";
import { palette } from "@palette";
import { useGetUser } from "@services/api/onboarding/user";
import { getRelativeTime } from "@utils/date.helpers";
import React, { useEffect, useMemo, useState } from "react";
import { useFormContext } from "react-hook-form";
import RequirementBox from "./RequirementBox";
import TrustedDevices from "./TrustedDevices";
import {
  PASSWORD_HAS_LOWERCASE_REGEX,
  PASSWORD_HAS_NUMBER_REGEX,
  PASSWORD_HAS_SPECIAL_CHAR_REGEX,
  PASSWORD_HAS_UPPERCASE_REGEX,
} from "@validation/regex";
 
type ResetPasswordProps = {
  setDisabled: React.Dispatch<React.SetStateAction<boolean>>;
};
 
const ResetPassword = ({ setDisabled }: ResetPasswordProps) => {
  const { data: userData } = useGetUser();
  const { watch, getFieldState } = useFormContext();
  const values = watch();
 
  const lastTimePasswordWasUpdated = useMemo(() => {
    const _date = getRelativeTime(
      (userData?.passwordLastChangedAt || 0) * 1000,
    );
    return {
      isExpiring: !!_date.expiresIn,
      message: _date.elapsedTime || _date.expiresIn,
    };
  }, [userData]);
 
  const isDisabledPassword =
    values.confirm_password !== values.new_password ||
    values.new_password.length < 8 ||
    !/[0-9]/.test(values.new_password) ||
    values.current_password.length < 4;
 
  useEffect(() => {
    setDisabled(isDisabledPassword);
  }, [isDisabledPassword]);
 
  const [visibleCurrentPassword, setVisibleCurrentPassword] = useState(false);
  const [visibleNewPassword, setVisibleNewPassword] = useState(false);
  const [visibleConfirmPassword, setVisibleConfirmPassword] = useState(false);
 
  useEffect(() => {
    setDisabled(isDisabledPassword);
  }, [isDisabledPassword]);
 
  const passwordInputs = [
    {
      name: "current_password",
      label: "Current password",
      placeholder: "Current Password",
      type: !visibleCurrentPassword ? "text" : "password",
      InputProps: {
        endAdornment: (
          <EndAdornment
            isVisible={visibleCurrentPassword}
            setIsVisible={setVisibleCurrentPassword}
          />
        ),
      },
    },
    {
      name: "new_password",
      label: "New Password",
      placeholder: "Type your new password",
      type: !visibleNewPassword ? "text" : "password",
      InputProps: {
        endAdornment: (
          <EndAdornment
            isVisible={visibleNewPassword}
            setIsVisible={setVisibleNewPassword}
          />
        ),
      },
    },
    {
      name: "confirm_password",
      label: "Confirm Password",
      placeholder: "Re-type your new password",
      type: !visibleConfirmPassword ? "text" : "password",
      InputProps: {
        endAdornment: (
          <EndAdornment
            isVisible={visibleConfirmPassword}
            setIsVisible={setVisibleConfirmPassword}
          />
        ),
      },
      error: !!(
        values.confirm_password &&
        values.confirm_password !== values.new_password
      ),
      helper:
        values.confirm_password &&
        values.confirm_password !== values.new_password
          ? " Passwords do not match"
          : "",
    },
  ];
 
  const lastTimeUpdate = {
    color: lastTimePasswordWasUpdated.isExpiring
      ? palette.filled.red
      : "#326EC5",
    message: !lastTimePasswordWasUpdated.isExpiring
      ? `Last updated ${lastTimePasswordWasUpdated.message}`
      : lastTimePasswordWasUpdated.message,
  };
 
  return (
    <Box>
      <Text color={palette.neutral[80]} fontWeight="book" fontSize={18} mb={2}>
        Password
      </Text>
      <Text color={lastTimeUpdate.color} mb={1}>
        {lastTimeUpdate.message}
      </Text>
      <Text fontWeight="book" color={palette.neutral[70]}>
        Passwords are the first line of defence against unauthorised access to
        your account. By refreshing your password every 90 days, you’re highly
        reducing the risk of potential threats.
      </Text>
      <Stack spacing={2} mt={3}>
        {passwordInputs.map((props) => (
          <RHFInput
            key={props.name}
            {...props}
            fullWidth
            inputProps={{ maxLength: 254 }}
          />
        ))}
 
        <Stack spacing={1}>
          {requirementsList.map((item, index) => {
            return (
              <RequirementBox
                key={index}
                requirement={item.text}
                color={
                  getFieldState("new_password").isDirty ||
                  getFieldState("new_password").isTouched ||
                  getFieldState("new_password").invalid ||
                  values.new_password.length > 0
                    ? getNewErrorColor(item.type, values.new_password)
                    : palette.neutral[200]
                }
              />
            );
          })}
        </Stack>
      </Stack>
 
      <Divider sx={{ paddingY: "8px" }} />
      <TrustedDevices />
    </Box>
  );
};
 
const EndAdornment = ({
  isVisible,
  setIsVisible,
}: {
  isVisible: boolean;
  setIsVisible: React.Dispatch<React.SetStateAction<boolean>>;
}) => (
  <InputAdornment
    position="end"
    sx={{ mr: "2px !important", cursor: "pointer" }}
    onClick={() => setIsVisible((prev) => !prev)}
  >
    {!isVisible ? (
      <InputEyeIcon path_fill={palette.neutral[70]} />
    ) : (
      <InputEyeIconNotVisible path_fill={palette.neutral[70]} />
    )}
  </InputAdornment>
);
 
const requirementsList = [
  {
    type: "minCharacters",
    text: `${PASSWORD_MIN_CHARS} Characters minimum`,
  },
  {
    type: "lowercase",
    text: "One lowercase character",
  },
  {
    type: "specialCharacter",
    text: "One special character",
  },
  {
    type: "uppercase",
    text: "One uppercase character",
  },
  {
    type: "number",
    text: "One number",
  },
];
 
const getNewErrorColor = (type: string, value: string) => {
  switch (type) {
    case "minCharacters":
      return value.length >= PASSWORD_MIN_CHARS
        ? palette.filled.green
        : palette.filled.red;
    case "number":
      return PASSWORD_HAS_NUMBER_REGEX.test(value)
        ? palette.filled.green
        : palette.filled.red;
    case "uppercase":
      return PASSWORD_HAS_UPPERCASE_REGEX.test(value)
        ? palette.filled.green
        : palette.filled.red;
    case "lowercase":
      return PASSWORD_HAS_LOWERCASE_REGEX.test(value)
        ? palette.filled.green
        : palette.filled.red;
    case "specialCharacter":
      return PASSWORD_HAS_SPECIAL_CHAR_REGEX.test(value)
        ? palette.filled.green
        : palette.filled.red;
    default:
      return palette.filled.red;
  }
};
 
export default ResetPassword;