AvatarDropdown.jsx 5.35 KB
Newer Older
wuhao's avatar
wuhao committed
1 2
import React, { useCallback, useState, useMemo } from "react";
import { LogoutOutlined, LockOutlined } from "@ant-design/icons";
wuhao's avatar
wuhao committed
3
import { Menu, Spin, Form, Modal, message, Avatar } from "antd";
wuhao's avatar
wuhao committed
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
import { history, useModel, useRequest } from "umi";
import { stringify } from "querystring";
import HeaderDropdown from "../HeaderDropdown";
import styles from "./index.less";
import { fakeAccountLoginOut, changePwd } from "@/services/login";
import InitForm from "@/components/InitForm";
import { doFetch } from "@/utils/doFetch";
import AES from "crypto-js/aes";
import ECB from "crypto-js/mode-ecb";
import Pkcs7 from "crypto-js/pad-pkcs7";
import Utf8 from "crypto-js/enc-utf8";
import moment from "moment";
/**
 * 退出登录,并且将当前的 url 保存
 */
const loginOut = async () => {
  await fakeAccountLoginOut();
  const { query = {} } = history.location;
  const { redirect } = query; // Note: There may be security issues, please note

  if (window.location.pathname !== "/user/login" && !redirect) {
    localStorage.clear();
    history.replace("/user/login");
  }
};

const AvatarDropdown = ({ menu }) => {
  const { initialState, setInitialState } = useModel("@@initialState");
  const [visible, cv] = useState(false),
    [formRef] = Form.useForm(),
    { run, loading } = useRequest(doFetch, {
      manual: true,
      formatResult: (res) => res,
      onSuccess: (result, params) => {
        if (result.code == "0000") {
          cv(false);
          message.success("密码修改成功,请重新登录", 2, () => {
            setInitialState((s) => ({
              ...s,
              currentUser: undefined,
              newMenu: undefined,
            }));
            loginOut();
          });
        }
      },
    });
  const fields = useMemo(() => {
    return {
      password: {
        value: null,
        type: "password",
        title: "密码",
        name: ["password"],
        required: true,
      },
      newPassword: {
        value: null,
        type: "password",
        title: "新密码",
        name: ["newPassword"],
        required: true,
      },
      confirmPassword: {
        value: null,
        type: "password",
        title: "确认密码",
        name: ["confirmPassword"],
        required: true,
        checkConfirm: (rule, value) => {
          if (value && value !== formRef.getFieldValue("newPassword")) {
            return Promise.reject("2次密码不一致!");
          } else {
            return Promise.resolve();
          }
        },
      },
    };
  }, []);
  const onMenuClick = useCallback(
    (event) => {
      const { key } = event;
      if (key === "logout") {
        setInitialState((s) => ({
          ...s,
          currentUser: undefined,
          newMenu: undefined,
        }));
        loginOut();
        return;
      } else if (key == "changepwd") {
        cv(true);
        return;
      }
      history.push(`/account/${key}`);
    },
    [setInitialState]
  );
  const loadings = (
    <span className={`${styles.action} ${styles.account}`}>
      <Spin
        size="small"
        style={{
          marginLeft: 8,
          marginRight: 8,
        }}
      />
    </span>
  );

  if (!initialState) {
    return loadings;
  }

  const { currentUser } = initialState;
  if (!currentUser || !currentUser.userName) {
    return loadings;
  }

  let saveData = (values) => {
    let newfields = JSON.parse(JSON.stringify(values));
    delete newfields.confirmPassword;

    let timestamp = moment().valueOf().toString() + "acb";
    let newtimestamp = AES.encrypt(timestamp, Utf8.parse("NANGAODEAESKEY--"), {
      mode: ECB,
      padding: Pkcs7,
    }).toString();
    let newPassword = AES.encrypt(values.newPassword, Utf8.parse(timestamp), {
wuhao's avatar
wuhao committed
133 134 135
      mode: ECB,
      padding: Pkcs7,
    }).toString(),
wuhao's avatar
wuhao committed
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
      password = AES.encrypt(values.password, Utf8.parse(timestamp), {
        mode: ECB,
        padding: Pkcs7,
      }).toString();

    let postData = {
      password,
      newPassword,
      encryptKey: newtimestamp,
    };
    run({ url: "/ngic-auth/sysUser/changePassword", params: { ...postData } });
  };

  const menuHeaderDropdown = (
    <Menu className={styles.menu} selectedKeys={[]} onClick={onMenuClick}>
      <Menu.Item key="changepwd">
        <LockOutlined />
        修改密码
      </Menu.Item>
      <Menu.Divider />
      <Menu.Item key="logout">
        <LogoutOutlined />
        退出登录
      </Menu.Item>
    </Menu>
  );
  return (
    <div>
      <Modal
        title="修改密码"
        visible={visible}
        onCancel={() => {
          cv(false);
        }}
        destroyOnClose={true}
        maskClosable={false}
        footer={false}
      >
        <InitForm
          formRef={formRef}
          fields={fields}
          col={{ span: 24 }}
wuhao's avatar
wuhao committed
178
          onChange={(changedValues, allValues) => { }}
wuhao's avatar
wuhao committed
179 180 181 182
          submitData={(values, fn) => {
            saveData(values, fn);
          }}
          submitting={loading || !visible}
wuhao's avatar
wuhao committed
183 184
        >
        </InitForm>
wuhao's avatar
wuhao committed
185 186 187
      </Modal>
      <HeaderDropdown overlay={menuHeaderDropdown}>
        <span className={`${styles.action} ${styles.account}`}>
wuhao's avatar
wuhao committed
188 189
          <Avatar style={{marginRight:12,backgroundColor:"#1890ff"}}>{currentUser.userName.substr(0,1)}</Avatar>

wuhao's avatar
wuhao committed
190 191 192 193 194 195 196 197 198 199
          <span className={`${styles.name} anticon`}>
            {currentUser.userName}
          </span>
        </span>
      </HeaderDropdown>
    </div>
  );
};

export default AvatarDropdown;