All files / src/security LoginPage.tsx

75.86% Statements 44/58
57.77% Branches 26/45
81.81% Functions 9/11
75.86% Lines 44/58

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                                  7x             7x             7x 33x 31x 31x 31x 31x 31x 31x 31x 31x   31x 1x 1x   1x   1x   1x 1x   1x     31x 2x 2x 1x 1x 1x     1x 1x 1x       27x 11x                 27x                       27x 11x         27x 10x           27x 1x     27x 2x     27x 27x 27x                       27x                                                                                                                                                                                                              
import React, { ReactElement, useCallback, useEffect, useState } from "react";
import { Form, Input, Button, Space, Popover } from 'antd';
import {
  WarningOutlined, LoadingOutlined, LockOutlined, UserOutlined,
} from '@ant-design/icons';
import { useTranslation } from 'react-i18next';
import { login, logout, Credentials, loggedIn } from "@utils/LoginUtils";
import { getDefaultPage } from "@utils/TokenUtils";
import { isDevelopmentEnv } from "@config/base";
import { QuickLoginPanel, SwitchLanguage } from "../development";
import { Link } from "react-router-dom";
import { useTheme } from "@utils/hooks";
import { layout, tailLayout } from "./layoutConfig";
import { useConfig } from "@utils/hooks";
 
import './login.less';
 
const TenantToEmailSuffixMapping: { [propName: string]: string } = isDevelopmentEnv() ? {
  'samt': 'samtc.com',
  'aecc': 'aecc.cn',
  'clokm': 'boe.com',
  'muyan': 'muyan.cloud'
} : {};
 
export const getEmailSuffix = (): string => {
  const { hostname } = window.location;
  const tenant = hostname.split('.')[0];
  const suffix = TenantToEmailSuffixMapping[tenant] || 'muyan.cloud';
  return suffix;
};
 
const LoginPage = (props: { next: string, firstTime?: boolean }): ReactElement => {
  const { t } = useTranslation();
  const { next, firstTime } = props;
  const [loginSuccess, setLoginSuccess] = useState<boolean>(true);
  const [errorMsg, setErrorMsg] = useState<string>("");
  const [loading, setLoading] = useState<boolean>(false);
  const [form] = Form.useForm();
  const themeInfo = useTheme();
  const { value: registerEnable } = useConfig('register.self_register');
  const { value: resetPasswordEnable } = useConfig('register.reset_password');
 
  const redirectToConfigPage = useCallback((): void => {
    const defaultPage = getDefaultPage();
    let assignUrl = '/';
    // 仅在 next 不为 / 时,优先级高于 defaultPage
    Iif (next != null && next !== '/') {
      assignUrl = next;
    } else Iif (defaultPage != null && defaultPage !== '') {
      assignUrl = defaultPage;
    } else Eif (next != null) {
      assignUrl = next;
    }
    window.location.replace(assignUrl);
  }, [next]);
 
  const onFinish = useCallback((values: Credentials): void => {
    setLoading(true);
    login(values, themeInfo.ssoEnable).then(() => {
      Eif (loggedIn()) {
        setLoading(false);
        redirectToConfigPage();
      }
    }).catch((e) => {
      setLoginSuccess(false);
      setLoading(false);
      setErrorMsg(e.message);
    });
  }, [redirectToConfigPage, themeInfo.ssoEnable]);
 
  useEffect(() => {
    Iif (themeInfo.ssoEnable) {
      onFinish({
        username: '',
        password: '',
        rememberMe: ''
      });
    }
  }, [themeInfo.ssoEnable, onFinish]);
 
  const setLoginInfo = useCallback((email: string, autoLogin?: boolean): void => {
    const cre: Credentials = {
      username: email,
      password: "password",
      rememberMe: "false",
    };
    form.setFieldsValue(cre);
    if (autoLogin) {
      onFinish(cre);
    }
  }, [form, onFinish]);
 
  useEffect(() => {
    Iif (firstTime === true) {
      setLoginInfo(`admin@${getEmailSuffix()}`, false);
    }
  }, [firstTime, setLoginInfo]);
 
  useEffect(() => {
    Iif (loggedIn()) {
      setLoading(false);
      redirectToConfigPage();
    }
  }, [redirectToConfigPage, loginSuccess, errorMsg, t]);
 
  const onFinishFailed = (errorInfo: unknown): void => {
    console.error(`Failed to login: ${JSON.stringify(errorInfo)}`);
  };
 
  if (next === "/logout") {
    logout();
  }
 
  const widthStyle = { width: "300px" };
  const userIcon = <UserOutlined className="site-form-item-icon" />;
  const loginPrefix = isDevelopmentEnv() ? (
    <Popover
      title={undefined}
      placement="left"
      content={<QuickLoginPanel
        setLoginInfo={setLoginInfo}
      />}
    >
      {userIcon}
    </Popover>
  ) : userIcon;
 
  return loggedIn() ? (<></>) : (
    <div>
      <div className="login-div">
        <Space direction="vertical">
          {themeInfo?.logo &&
            <div className="login-logo">
              <img
                src={themeInfo.logo}
                style={{ maxWidth: '240px' }}
              />
            </div>
          }
          <Form
            className="login-form"
            {...layout}
            name="basic"
            initialValues={{ remember: true }}
            onFinish={onFinish}
            onFinishFailed={onFinishFailed}
            size="large"
            colon={false}
            form={form}
          >
            <Form.Item
              name="username"
              rules={[{ required: true, message: t('login:Please input your email') }]}
            >
              <Input
                prefix={loginPrefix}
                style={widthStyle}
                placeholder={t("login:Please input your email")}
              />
            </Form.Item>
 
            <Form.Item
              name="password"
              rules={[{ required: true, message: t('login:Please input your password') }]}
            >
              <Input.Password
                prefix={<LockOutlined className="site-form-item-icon" />}
                style={widthStyle}
                placeholder={t("login:Please input your password")}
              />
            </Form.Item>
 
            <Form.Item {...tailLayout} valuePropName="checked">
              {/*<Checkbox>Remember me</Checkbox>*/}
              {!loading &&
                <Button
                  type="primary"
                  htmlType="submit"
                >
                  {t("login:LoginButtonLabel")}
                </Button>
              }
              {loading &&
                <Button
                  type="primary"
                  htmlType="submit"
                  disabled={true}
                  icon={<LoadingOutlined />}>
                  {t('login:KnockingTheDoor')}
                </Button>}
              {!loginSuccess &&
                <span className="login-failed-msg">
                  <WarningOutlined className="login-failed-msg" />{errorMsg}
                </span>
              }
            </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
              }}>
                {registerEnable &&
                  <Link
                    to='/account?scene=register'
                  >
                    {t('account:Register new account')}
                  </Link>
                }
                <div style={{ textAlign: 'center', flex: '1' }}>
                  <SwitchLanguage />
                </div>
                {resetPasswordEnable &&
                  <Link
                    to='/account?scene=resetPassword'
                  >
                    {t('account:Forgot password')}
                  </Link>
                }
              </div>
            }
          </Form>
        </Space>
        <br />
      </div>
    </div>
  );
};
 
export default LoginPage;