All files / src/security AccountPage.tsx

73.23% Statements 52/71
59.52% Branches 25/42
75% Functions 12/16
73.23% Lines 52/71

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 333 334 335 336 337 338 339 340 341                                            7x               7x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x   26x 26x   26x 2x 2x 2x       1x   1x   2x       26x 2x       2x 2x 2x 2x 1x 1x 1x             1x   1x       2x       26x       26x   26x         26x         26x         26x                                                                                                                         4x         4x                           2x                 2x                                 4x     4x     4x                                   4x   4x 4x                                                                                                                                                                                              
import React, { ReactElement, useCallback, useState } from "react";
import { Button, Form, Input, Space } from 'antd';
import { CheckCircleTwoTone, LockOutlined, MailOutlined, UserOutlined } from '@ant-design/icons';
import { useTranslation } from 'react-i18next';
import PasswordValidator from "password-validator";
import { v4 as uuid } from 'uuid';
import {
  registerOrResetPassword,
  RegisterOrResetPasswordForm,
  sendVerificationCode,
  SendVerificationCodeForm
} from "@utils/AccountUtils";
import { Link } from "react-router-dom";
import { stopPropagationAndPreventDefault } from "@utils/ObjectUtils";
import { loggedIn } from "@utils/LoginUtils";
import { layout, tailLayout } from "./layoutConfig";
import { useConfig, useTheme } from "@utils/hooks";
import { openInfoNotification } from "@utils/NotificationUtils";
 
import './login.less';
import { SwitchLanguage } from "../development";
 
const validator = new PasswordValidator()
  .is().min(8)              // Minimum length 8
  .is().max(100)            // Maximum length 100
  .has().uppercase()        // Must have uppercase letters
  .has().lowercase()        // Must have lowercase letters
  .has().digits()           // Must have digits
  .has();                   // Should not have spaces
 
const AccountPage = (): ReactElement => {
  const { t } = useTranslation();
  const params = new URLSearchParams(window.location.search);
  const scene = params.get('scene') === 'resetPassword' ? 'resetPassword' : 'register';
  const invitationCode = scene === 'register' && params.get('invitationCode') || undefined;
  const [requestId] = useState<string>(uuid());
  const [validationCodeErrorMsg, setValidationCodeErrorMsg] = useState<string>("");
  const [submitErrorMsg, setSubmitErrorMsg] = useState<string>("");
  const [submitting, setSubmitting] = useState<boolean>(false);
  const [sendingVerificationCode, setSendingVerificationCode] = useState<boolean>(false);
  const [form] = Form.useForm<RegisterOrResetPasswordForm>();
  const [coolDown, setCoolDown] = useState<number>(0);
  const [success, setSuccess] = useState<boolean>(false);
  const themeInfo = useTheme();
 
  const { value: registerEnable } = useConfig('register.self_register');
  const { value: resetPasswordEnable } = useConfig('register.reset_password');
 
  const onFinish = useCallback((values: RegisterOrResetPasswordForm): void => {
    setSubmitErrorMsg("");
    setSubmitting(true);
    registerOrResetPassword(scene, requestId, {
      ...values,
      invitationCode,
    }).then(() => {
      setSuccess(true);
    }).catch((e) => {
      setSubmitErrorMsg(e.message);
    }).finally(() => {
      setSubmitting(false);
    });
  }, [invitationCode, requestId, scene]);
 
  const onSendVerificationCode = useCallback(async (values: SendVerificationCodeForm) => {
    Iif (!values.email) {
      setValidationCodeErrorMsg(t('account:Please input your email first'));
      return;
    }
    setSendingVerificationCode(true);
    setValidationCodeErrorMsg("");
    try {
      await sendVerificationCode(scene, requestId, values);
      let counter = 60;
      setCoolDown(counter);
      const timer = setInterval(() => {
        --counter;
        setCoolDown(counter);
        if (counter <= 0) {
          clearInterval(timer);
        }
      }, 1000);
      openInfoNotification(t('account:Verification code sent successfully'));
    } catch (e: unknown) {
      setValidationCodeErrorMsg(t('account:Failed to send verification code', {
        error: t(`account:${(e as { message: string }).message}`)
      }));
    } finally {
      setSendingVerificationCode(false);
    }
  }, [requestId, scene, t]);
 
  const onFinishFailed = (errorInfo: unknown): void => {
    console.error(`Failed to ${scene}: ${JSON.stringify(errorInfo)}`);
  };
 
  const widthStyle = { width: "300px" };
 
  Iif (loggedIn()) {
    window.location.href = "/";
    return <></>;
  }
 
  const sceneTitle = {
    "register": t("account:register title"),
    "resetPassword": t("account:resetPassword title")
  };
 
  const sceneSuccessMsg = {
    "register": t("account:register successfully"),
    "resetPassword": t("account:resetPassword successfully"),
  };
 
  return (
    <div className="login-div">
      <Space direction="vertical">
        {themeInfo?.logo &&
          <div className="login-logo">
            <img
              src={themeInfo.logo}
              style={{ maxWidth: '240px' }}
            />
          </div>
        }
        {!success
          ? (<>
            <Form
              className="login-form"
              {...layout}
              name="basic"
              initialValues={{
                remember: true,
              }}
              onFinish={onFinish}
              onFinishFailed={onFinishFailed}
              size="large"
              colon={false}
              form={form}
            >
              {scene === 'register' &&
                <Form.Item
                  name="name"
                  hasFeedback={true}
                >
                  <Input
                    prefix={<UserOutlined className="site-form-item-icon" />}
                    style={widthStyle}
                    placeholder={t("account:What should we call you?")}
                  />
                </Form.Item>
              }
              <Form.Item
                name="email"
                hasFeedback={true}
                rules={[
                  { required: true, message: t('account:Please input your email') },
                  {
                    type: 'email',
                    message: t('account:The input is not valid E-mail'),
                  },
                ]}
              >
                <Input
                  prefix={<MailOutlined />}
                  style={widthStyle}
                  placeholder={t("account:Please input your email")}
                />
              </Form.Item>
 
              <Form.Item
                name="verificationCode"
                rules={[
                  {
                    validator: (rule, value) => {
                      Iif (!value) {
                        const errMsg = t('account:Verification code could not be empty');
                        setValidationCodeErrorMsg(errMsg);
                        return Promise.reject(errMsg);
                      }
                      return Promise.resolve();
                    }
                  }
                ]}
                style={{
                  width: '100%',
                }}
                validateStatus={validationCodeErrorMsg ? 'error' : 'success'}
                help={`${validationCodeErrorMsg}`}
              // help={!!validationCodeErrorMsg ? <div>{validationCodeErrorMsg}</div> : undefined}
              >
                <Space direction={'horizontal'}>
                  <Input
                    onChange={(e) => {
                      form.setFieldValue('verificationCode', e.target.value);
                    }}
                    placeholder={t("account:Please input verification code")}
                  />
                  <Button
                    type="primary"
                    disabled={sendingVerificationCode || coolDown > 0}
                    loading={sendingVerificationCode}
                    onClick={() => {
                      onSendVerificationCode({
                        email: form.getFieldValue('email'),
                      });
                    }}
                  >
                    {coolDown > 0 ? `${coolDown}s` : t("account:Get Verification Code")}
                  </Button>
                </Space>
              </Form.Item>
 
              <Form.Item
                name="password"
                hasFeedback={true}
                rules={[
                  { required: true, message: t('account:Please input your password') },
                  {
                    validator: async (_, value) => {
                      Iif (!value) {
                        return Promise.resolve();
                      }
                      Iif (!validator.validate(value)) {
                        return Promise.reject(new Error(t("account:Min length 8, use Aa & 0-9")));
                      }
                      return Promise.resolve();
                    }
                  },
                ]}
              >
                <Input.Password
                  prefix={<LockOutlined className="site-form-item-icon" />}
                  style={widthStyle}
                  placeholder={t("account:Min length 8, use Aa & 0-9")}
                />
              </Form.Item>
 
              <Form.Item
                name="confirmedPassword"
                hasFeedback={true}
                dependencies={['password']}
                rules={[
                  { required: true, message: t('account:Please input your password again') },
                  ({ getFieldValue }) => ({
                    validator(_, value) {
                      Eif (getFieldValue('password') === value) {
                        return Promise.resolve();
                      }
                      return Promise.reject(new Error(t('account:The two passwords that you entered do not match')));
                    },
                  }),
                ]}
              >
                <Input.Password
                  prefix={<LockOutlined className="site-form-item-icon" />}
                  style={widthStyle}
                  placeholder={t("account:Please input your password again")}
                />
              </Form.Item>
 
              <Form.Item
                {...tailLayout}
                valuePropName="checked"
                validateStatus={submitErrorMsg ? 'error' : 'success'}
                help={`${submitErrorMsg}`}
              >
                <Button
                  type="primary"
                  htmlType="submit"
                  disabled={submitting}
                  loading={submitting}
                >
                  {sceneTitle[scene]}
                </Button>
              </Form.Item>
              {(registerEnable || resetPasswordEnable) &&
                <div style={{
                  display: 'flex',
                  justifyContent: 'space-between', // This will evenly distribute the items
                  alignItems: 'center', // Vertically center align items if needed
                }}>
                  <Link
                    to='/login'
                    style={{
                      float: 'left'
                    }}
                  >
                    {t('login:Login')}
                  </Link>
                  <div style={{ textAlign: 'center', flex: '1' }}>
                    <SwitchLanguage />
                  </div>
                  {scene === 'resetPassword' ? (registerEnable && <Link
                    to='/account?scene=register'
                    style={{
                      float: 'right'
                    }}
                    onClick={(e) => {
                      window.location.href = "/account?scene=register";
                      stopPropagationAndPreventDefault(e);
                    }}
                  >
                    {t('account:Register new account')}
                  </Link>
                  )
                    : (resetPasswordEnable && <Link
                      to='/account?scene=resetPassword'
                      style={{
                        float: 'right'
                      }}
                      onClick={(e) => {
                        window.location.href = "/account?scene=resetPassword";
                        stopPropagationAndPreventDefault(e);
                      }}
                    >{t('account:Forgot password')}</Link>)
                  }
                </div>
              }
            </Form>
          </>
          ) : (
            <Space className="login-form" direction={'vertical'} align={'center'} size={30}>
              <CheckCircleTwoTone
                style={{ fontSize: '1000%' }}
                twoToneColor={'#00EE00'}
              />
              <div style={{ fontSize: '24px' }}>
                {sceneSuccessMsg[scene]}
              </div>
              <Link to='/login'>
                {t('account:Back to login')}
              </Link>
            </Space>
          )
        }
      </Space>
    </div>
  );
};
 
export default AccountPage;