EditUserModal.jsx 13.9 KB
Newer Older
1
/* eslint-disable import/no-unresolved */
2
import React, { useEffect, useState } from 'react';
3
import { Modal, Form, Input, notification, message, Divider } from 'antd';
4
import voca from 'voca';
5 6 7 8
import classNames from 'classnames';
import { editUser, updateUserPassword } from '@/services/userManage/api';
import sha1 from 'sha1';
import styles from './AddUserModal.less';
9 10

const EditUserModal = props => {
11
  const { visible, currentUser, currentSelectOrg, onCancel, onSelect, submitSearchUser } = props;
12 13 14 15 16 17 18
  const [editUserForm] = Form.useForm(); // 编辑用户
  /** ***正则验证**** */
  const noChinese = new RegExp(/^[^\u4e00-\u9fa5]+$/); // 不能包含中文
  const isPhone = new RegExp(/^1(3|4|5|6|7|8|9)\d{9}$/); // 手机号
  const isEmail = new RegExp(
    /^[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*@[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*\.[a-z]{2,}$/,
  ); // 邮箱
19 20 21
  const [passwordForm] = Form.useForm(); // 修改密码
  const [newPasswordLevel, setNewPasswordLevel] = useState('');
  const [passwordConfirmLevel, setPasswordConfirmLevel] = useState('');
22 23

  useEffect(() => {
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
    if (visible) {
      console.log(currentUser);
      editUserForm.setFieldsValue({
        loginName: voca.stripTags(currentUser.loginName),
        userName: voca.stripTags(currentUser.userName),
        phone: voca.stripTags(currentUser.phone) || '',
        email: currentUser.email || '',
      });
      console.log(currentUser.password);
      passwordForm.setFieldsValue({
        oldPassword: currentUser.password,
        newPassword: '',
        passwordConfirm: '',
      });
    } else {
      setNewPasswordLevel('');
      setPasswordConfirmLevel('');
    }
42
  }, [visible]);
43 44 45

  // 提交-编辑用户
  const submitEditUser = () => {
46 47 48
    const loginName = voca.stripTags(editUserForm.getFieldValue('loginName'));
    const userName = voca.stripTags(editUserForm.getFieldValue('userName'));
    const phone = voca.stripTags(editUserForm.getFieldValue('phone')) || '';
49
    const email = editUserForm.getFieldValue('email') || '';
50 51 52
    const oldPassword = passwordForm.getFieldValue('oldPassword');
    const newPassword = passwordForm.getFieldValue('newPassword');
    const passwordConfirm = passwordForm.getFieldValue('passwordConfirm');
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
    editUserForm.validateFields().then(validate => {
      // 正则验证
      if (loginName === '') {
        notification.error({
          message: '提交失败',
          description: '登录名称不能为空!',
        });
        return;
      }
      if (!noChinese.test(loginName)) {
        notification.error({
          message: '提交失败',
          description: '登录名不支持中文!',
        });
        return;
      }
      if (userName === '') {
        notification.error({
          message: '提交失败',
          description: '用户姓名不能为空!',
        });
        return;
      }
      if (phone !== '' && !isPhone.test(phone)) {
        notification.error({
          message: '提交失败',
          description: '请输入11位手机号!',
        });
        return;
      }
      if (email !== '' && !isEmail.test(email)) {
        notification.error({
          message: '提交失败',
          description: '邮箱格式不正确!',
        });
        return;
      }
      // if ((newPassword && passwordConfirm === '') || (passwordConfirm && newPassword === '')) {
      //   notification.error({
      //     message: '提交失败',
      //     description: '请填写密码',
      //   });
      //   return;
      // }
邓超's avatar
邓超 committed
97

98 99 100 101 102 103 104 105 106 107 108 109 110 111
      if ((newPassword && newPassword.length < 6) || (passwordConfirm && passwordConfirm < 6)) {
        notification.error({
          message: '提交失败',
          description: '密码至少为6位!',
        });
        return;
      }
      if (newPassword !== passwordConfirm) {
        notification.error({
          message: '提交失败',
          description: '确认密码不一致!',
        });
        return;
      }
邓超's avatar
邓超 committed
112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
      if (newPassword && newPassword) {
        if (newPasswordLevel === '弱') {
          notification.error({
            message: '提交失败',
            description: '密码强度太弱,加强密码强度',
          });
          return;
        }
        if (
          !/^(?=.*[a-zA-Z])(?=.*\d)[\w\S]{6,16}$/.test(newPassword) ||
          !/^(?!.*(?:SELECT|UPDATE|INSERT|AND|OR|'|"|;|--|\\)).*$/.test(newPassword)
        ) {
          notification.error({
            message: '提交失败',
            description: '密码验证未通过',
          });
          return;
        }
      }
131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
      // 所有验证通过才可以提交,phone/email为空时不验证
      if (
        loginName &&
        noChinese.test(loginName) &&
        userName &&
        (phone === '' || isPhone.test(phone)) &&
        (email === '' || isEmail.test(email))
      ) {
        editUser(currentUser.userId, loginName, userName, phone, email)
          .then(res => {
            if (res.msg === '') {
              onCancel();
              // 重新获取用户表
              if (!newPassword) {
                // eslint-disable-next-line no-unused-expressions
                currentSelectOrg === '-1' ? submitSearchUser() : onSelect([currentSelectOrg]);
              }
148

149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164
              notification.success({
                message: '提交成功',
                duration: 2,
              });
              submitChangePassword();
            } else {
              notification.error({
                message: '提交失败',
                description: res.message,
              });
            }
            editUserForm.setFieldsValue({
              loginName: voca.stripTags(currentUser.loginName),
              userName: voca.stripTags(currentUser.userName),
              phone: voca.stripTags(currentUser.phone) || '',
              email: currentUser.email || '',
165
            });
166 167 168
          })
          .catch(err => {
            message.error(err);
tianfen's avatar
tianfen committed
169
          });
170 171
      }
    });
172
  };
173 174 175 176 177 178 179 180 181
  const title = (
    <span>
      编辑用户
      <span style={{ fontWeight: 'bold', color: 'rgb(24, 144, 255)' }}>
{currentUser.userName}
      </span>
      的信息
    </span>
  );
182 183 184 185 186 187 188 189 190 191 192 193 194 195

  // 提交-修改密码
  const submitChangePassword = () => {
    const oldPassword = passwordForm.getFieldValue('oldPassword');
    const newPassword = passwordForm.getFieldValue('newPassword');
    const passwordConfirm = passwordForm.getFieldValue('passwordConfirm');
    if (
      newPassword &&
      newPassword.length >= 6 &&
      passwordConfirm &&
      newPassword.length >= 6 &&
      newPassword === passwordConfirm
    ) {
      updateUserPassword({
196
        UserId: +currentUser.userId,
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
        OldPassWord: oldPassword,
        NewPassWord: sha1(newPassword).toUpperCase(),
      })
        .then(res => {
          if (res.code === 0) {
            onCancel();
            // eslint-disable-next-line no-unused-expressions
            currentSelectOrg === '-1' ? submitSearchUser() : onSelect([currentSelectOrg]);
            // notification.success({
            //   message: '提交成功',
            //   duration: 2,
            // });
          } else {
            notification.error({
              message: '提交失败',
              description: res.message,
            });
          }
          passwordForm.setFieldsValue({
            oldPassword: currentUser.password,
            newPassword: '',
            passwordConfirm: '',
          });
        })
        .catch(err => {
          message.error(err);
        });
    }
  };
  const changeValue = changedFields => {
    if (changedFields[0].name[0] === 'newPassword') {
      setNewPasswordLevel(checkStrong(changedFields[0].value));
    }
    if (changedFields[0].name[0] === 'passwordConfirm') {
      setPasswordConfirmLevel(checkStrong(changedFields[0].value));
    }
  };
  const checkStrong = sValue => {
    let modes = 0;
    // 正则表达式验证符合要求的
    if (sValue.length < 1) return modes;
    if (/\d/.test(sValue)) modes++; // 数字
    if (/[a-z]/.test(sValue)) modes++; // 小写
    if (/[A-Z]/.test(sValue)) modes++; // 大写
    if (/[_\W]/.test(sValue)) modes++; // 特殊字符
    console.log(modes, 'modes');
    // 逻辑处理
    // eslint-disable-next-line default-case
    switch (modes) {
      case 1:
        return '弱';
      case 2:
        if (sValue.length > 8) {
          return '中';
        }
        return '弱';
      case 3:
        if (sValue.length > 8) {
          return '强';
        }
        return '中';
      case 4:
        return '强';
    }
  };
262 263
  return (
    <Modal
264
      title={title}
265
      visible={visible}
266 267
      maskClosable={false}
      destroyOnClose
268 269 270
      // afterClose={() => {
      //   editUserForm.resetFields();
      // }}
271
      onOk={submitEditUser}
tianfen's avatar
tianfen committed
272 273 274 275 276
      onCancel={() => {
        onCancel();
        editUserForm.setFieldsValue({
          loginName: voca.stripTags(currentUser.loginName),
          userName: voca.stripTags(currentUser.userName),
277 278
          phone: voca.stripTags(currentUser.phone) || '',
          email: currentUser.email || '',
tianfen's avatar
tianfen committed
279 280
        });
      }}
281 282 283 284
      okText="确认"
      cancelText="取消"
    >
      <Form form={editUserForm} labelCol={{ span: 4 }}>
285 286 287 288 289 290 291
        <Form.Item
          hasFeedback
          name="loginName"
          label="登录名称"
          rules={[
            {
              pattern: /^[a-zA-Z0-9_]{0,}$/,
邓超's avatar
邓超 committed
292
              message: '长度小于16位,支持字母与数字,允许下划线',
293 294 295 296
            },
            { required: true },
          ]}
        >
邓超's avatar
邓超 committed
297
          <Input placeholder="请输入登录名称(小于16位)" maxLength="16" />
298
        </Form.Item>
299 300 301 302 303 304
        <Form.Item
          hasFeedback
          name="userName"
          label="用户姓名"
          rules={[
            { required: true },
邓超's avatar
邓超 committed
305 306 307 308
            {
              pattern: /^[A-Za-z0-9_\u4e00-\u9fa5]+$/,
              message: '长度小于16位,支持字母、中文与数字,允许下划线',
            },
309 310
          ]}
        >
邓超's avatar
邓超 committed
311
          <Input placeholder="请输入用户姓名(小于16位)" maxLength="16" />
312 313
        </Form.Item>
        <Form.Item
皮倩雯's avatar
皮倩雯 committed
314
          hasFeedback
315 316 317
          name="phone"
          label="手机号码"
          rules={[
318
            { required: true },
319
            {
320
              pattern: new RegExp(/^1[0-9]{10}$/),
邓超's avatar
邓超 committed
321
              message: '请输入正确的手机号码!',
322 323 324
            },
          ]}
        >
邓超's avatar
邓超 committed
325
          <Input placeholder="请输入手机号码" autoComplete="off" maxlength="11" />
326 327
        </Form.Item>
        <Form.Item
皮倩雯's avatar
皮倩雯 committed
328
          hasFeedback
329 330 331 332 333
          name="email"
          label="电子邮箱"
          rules={[
            {
              type: 'email',
邓超's avatar
邓超 committed
334
              message: '请输入正确的电子邮箱!',
335 336 337 338 339 340
            },
          ]}
        >
          <Input placeholder="请输入电子邮箱" autoComplete="off" />
        </Form.Item>
      </Form>
341 342 343 344 345 346 347 348
      <Divider
        orientation="left"
        style={{
          borderTopColor: '#99bbe8',
          color: '#15428b',
          fontWeight: 700,
        }}
      >
邓超's avatar
邓超 committed
349
        重置密码(选填)
350
      </Divider>
351 352 353 354 355 356 357 358 359 360 361
      <div className={styles.modalContent}>
        <Form form={passwordForm} labelCol={{ span: 4 }} onFieldsChange={changeValue}>
          <Form.Item name="oldPassword" label="原始密码">
            <Input disabled />
          </Form.Item>
          <div className={styles.formBox}>
            <Form.Item
              name="newPassword"
              label="新密码"
              rules={[
                {
邓超's avatar
邓超 committed
362 363 364 365 366 367
                  pattern: /^(?=.*[a-zA-Z])(?=.*\d)[\w\S]{6,16}$/,
                  message: '长度6-16位,必须包含数字与字母',
                },
                {
                  pattern: /^(?!.*(?:SELECT|UPDATE|INSERT|AND|OR|'|"|;|--|\\)).*$/,
                  message: '当前密码存在sql注入风险,请重新输入', // 防止sql注入
368
                },
369
                // { required: true },
370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400
              ]}
            >
              <Input.Password
                placeholder="请输入新密码"
                autoComplete="off"
                maxLength="16"
                onCopy={e => {
                  e.preventDefault();
                }}
                onPaste={e => {
                  // 禁止粘贴
                  e.preventDefault();
                }}
              />
            </Form.Item>
            <div
              className={classNames(styles.tipsText, {
                [styles.tipsRed]: newPasswordLevel === '弱',
                [styles.tipsOrange]: newPasswordLevel === '中',
                [styles.tipsGreen]: newPasswordLevel === '强',
              })}
            >
              {newPasswordLevel}
            </div>
          </div>
          <div className={styles.formBox}>
            <Form.Item
              name="passwordConfirm"
              label="确认密码"
              rules={[
                {
邓超's avatar
邓超 committed
401 402 403 404 405 406
                  pattern: /^(?=.*[a-zA-Z])(?=.*\d)[\w\S]{6,16}$/,
                  message: '长度6-16位,必须包含数字与字母',
                },
                {
                  pattern: /^(?!.*(?:SELECT|UPDATE|INSERT|AND|OR|'|"|;|--|\\)).*$/,
                  message: '当前密码存在sql注入风险,请重新输入', // 防止sql注入
407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434
                },
              ]}
            >
              <Input.Password
                placeholder="再次确认新密码"
                autoComplete="off"
                maxLength="16"
                onCopy={e => {
                  e.preventDefault();
                }}
                onPaste={e => {
                  // 禁止粘贴
                  e.preventDefault();
                }}
              />
            </Form.Item>
            <div
              className={classNames(styles.tipsText, {
                [styles.tipsRed]: passwordConfirmLevel === '弱',
                [styles.tipsOrange]: passwordConfirmLevel === '中',
                [styles.tipsGreen]: passwordConfirmLevel === '强',
              })}
            >
              {passwordConfirmLevel}
            </div>
          </div>
        </Form>
      </div>
435 436 437 438 439
    </Modal>
  );
};

export default EditUserModal;