login.js 13.4 KB
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 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 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 401 402 403 404 405 406 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 435
import React from 'react'
import './login.less'
import axios from '@src/axios/index'
import Ajax from 'axios'
import SYS_CONFIG from '@src/config/constant.js'
import Utils from '@src/utils/utils'
import storage from '@src/utils/localStorage'
import { withRouter } from 'react-router-dom';
import { API_USER_MANAGE, API_IMG_CODE, API_SYSPARAM_MANAGE } from '@src/Api'
import { Row, Modal, Col, Input, Icon, Form, Button, Checkbox, message } from 'antd'
const FormItem = Form.Item;
class Login extends React.Component {
  state = {
    userInfo: {},
    imgCodeShow: {display: 'none'},
    errorCount: 0,
    allowErrorCount: '', // 允许错误次数
    imgTimeNow: null,
    imgOutNum: 30,

  }

  componentDidMount() {
    //获取验证码
    // this.getImgCode()
    //获取本地登录信息
    this.getUserInfo()
    //获取允许错误次数
    this.getErrorCount();
    // 添加键盘事件监听
    window.addEventListener('keypress', (e) => {
      if (e.which == 13 || e.keyCode == 13) {
        this.submit();
      }
    })

  }
  
  getUserInfo = () => {
    const userInfo = storage.get('userInfo')
    console.log(userInfo);
    
    if (userInfo && Object.keys(userInfo).length > 0) {
      this.setState({ userInfo })
      //判断是否登录,如果已经登录直接跳转到home页面
      if(!userInfo.token=='')
      this.props.history.push({
        pathname: '/home'
      });
    }

  }

  // 获取允许输入错误次数
  getErrorCount = () => {
    axios.ajax({
      url: API_SYSPARAM_MANAGE.getParamKeyValueByKeyName,
      data: {keyName: 'sys.VerificationCode'}
    }).then((res) => {
      this.setState({allowErrorCount: parseInt(res)}, () => {
        // 从缓存读取错误次数
        if (storage.get('errorCount')) {
          let errorCount = storage.get('errorCount');
          if (errorCount >= this.state.allowErrorCount) {
            // 展示验证码
            this.setState({imgCodeShow: {display: 'block'}});
            this.getImgCode();
          }
        }
      });

    });
  }

  //获取验证码
  getImgCode = () => {
    axios.ajax({
      url: API_IMG_CODE.getImgCode
    }).then(res => {
      if (res) {
        this.setState({
          imgCode: res.img,
          img_code: res.img_code
        })
        this.getTimeOut()
      }
    })
  }

  getTimeOut() {
    let now =  Date.parse(new Date())   
    axios.ajax({
      url: API_SYSPARAM_MANAGE.getParamKeyValueByKeyName,
      data: {keyName: 'sys.verificationCodeTermOfValidity'}
    }).then((res) => {
       this.setState({
          imgTimeNow: now,
          imgOutNum: res ? +res : 30
        })
    });

  }
  //校验验证码
  verifyImgCode = (code) => {
    return new Promise((resolve, reject) => {
      let img_code = this.state.img_code
     
      if (code && img_code) {
        Ajax({
          url: API_IMG_CODE.verifyImgCode,
          baseURL: SYS_CONFIG.baseApi,
          method: 'POST',
          headers: { 'Content-Type': 'application/json; charset=UTF-8', },
          data: {
            code,
            key: img_code
          }
        }).then(res => {
          if (res.status === 200) {
            if (res.data.code == 0) {
              resolve(true)
            } else {
             
               
               let now =  Date.parse(new Date());
               const diff = now - this.state.imgTimeNow

               if (diff > this.state.imgOutNum*1000) {
                  message.error('验证码超时')
                  this.getImgCode()
                  return 
               } else {
                  this.getImgCode()
                  resolve(false)
               }

              
            }
          }
        }).catch(err => {
          resolve(false)
          message.error('请求超时,请重试')
        })

      } else {
        resolve(false)
      }
    })
  }


  //过滤空格
  filterSpace = (e, field) => {
    let inputLength = e.target.value.length;
    if (inputLength >= 64) {
      this.showErrorInfo('输入账户名超出了64位字符限制');
      let inputCode = e.target.value.substring(0, 64);
      this.props.form.setFieldsValue({loginName: inputCode});
    }
    let userInfo = this.props.form.getFieldsValue();
    if (e.keyCode == 32 || userInfo[field]) {
      this.props.form.setFieldsValue({ [field]: userInfo[field].replace(/^\s+|\s+$/g, '') })
    }
  }

  //显示错误信息
  showErrorInfo = (tips) => {
    this.setState({
      showError: true,
      tips
    })
  }

  //登录账号验证
  validLoginName = (rule, value, callback) => {
    var reg = /^[0-9a-zA-Z@_.]*$/g
    if (reg.test(value) === false) {
      this.showErrorInfo('请输入数字字母下划线')
      return false;
    }
    callback()
    this.showErrorInfo('')
  }


  submit = () => {
    // 如果记录了第一次出错
    if (storage.get('startTime')) {
      let endTime = new Date();
      // 如果第二次提交时间在第一次出错提交60秒后
      if (endTime.getTime() - new Date(storage.get('startTime')).getTime() >= 60000) {
        // 清空错误次数 清空开始时间
        storage.remove('errorCount');
        storage.remove('startTime');
      } 
    }
    let userInfo = Utils.trim(this.props.form.getFieldsValue());
    this.props.form.validateFields(async (err, values) => {

      if (!userInfo.loginName ||!userInfo.loginName.replace(/^\s+|\s+$/g, '') || userInfo.loginName == null) {
        this.showErrorInfo('请输入账户名')
        return
      } else if (!userInfo.password || userInfo.password == null) {
        this.showErrorInfo('请输入账户密码')

        return
        // 校验验证码
      } else if (this.state.imgCodeShow.display == 'block') {
        if (!userInfo.code || userInfo.code == null) {
          this.showErrorInfo('请输入验证码');
          return
        }
      }
      // } else if (!userInfo.code || userInfo.code == null) {
      //   this.showErrorInfo('请输入验证码')
      //   return
      // }

      //校验验证码
      let flag;
      if (this.state.imgCodeShow.display == 'block') {
        flag = await this.verifyImgCode(userInfo.code)
      } else {
        flag = true;
      }
      if (flag) {
        if (!err) {
          this.setState({
            showError: false,
            tips: ''
          })
          
          Ajax({
            url: API_USER_MANAGE.login,
            baseURL: SYS_CONFIG.baseApi,
            method: 'POST',
            headers: { 'Content-Type': 'application/json; charset=UTF-8', },
            data: {
              loginName: userInfo.loginName,
              password: userInfo.password
            }
          }).then(resp => {
            
            if (resp.status === 200) {
              if (resp.data.code == 0) {
                let res = resp.data.data
                if (userInfo && userInfo.remberUserName) {
                  res = Object.assign(res, { remberUserName: true })
                }
  
                if (userInfo && userInfo.remberPwd) {
                  res = Object.assign(res, { remberPwd: true })
                  res.password = userInfo.password
                }
                storage.set('userInfo', res)
                storage.get('userInfo')
                storage.remove('errorCount');
                storage.remove('startTime');
                this.props.history.push('/home');
              } else {
                // 登录失败
                let errorCount;
                if (storage.get('errorCount')) {
                  // 有错误次数
                  errorCount = storage.get('errorCount') + 1;
                  storage.set('errorCount', errorCount);
                } else {
                  // 记录第一次错误
                  storage.set('errorCount', 1);
                  // 记录第一次错误时间
                  let startTime = new Date();
                  storage.set('startTime',startTime);
                }
                
                if (storage.get('errorCount') >= this.state.allowErrorCount) {
                  // 展示验证码
                  this.getImgCode()
                  this.setState({imgCodeShow:{display: 'block'}});
                } else {
                  // 不展示验证码
                  this.setState({imgCodeShow:{display: 'none'}});
                }
                
                Modal.info({
                  title: '提示',
                  content: resp.data.msg
                })
                console.log(resp.data)
              }
              
            }
          }).catch(err => {
            message.error('请求超时,请重试')
          })

        } else {
          message.error('用户名或密码错误')
          this.getImgCode()
        }

      } else {

        this.getImgCode()
        message.error('验证码错误')
        return
      }


    })
  }


  render() {
    const { tips, showError } = this.state
    const iconStyle = {
      fontSize: 20,
      margin: -5,
      width: 20
    },
      inputStyle = {
        textAlign: 'center'
      },
      rowStyle = {
        marginTop: 10
      },
      { getFieldDecorator } = this.props.form


    return (
      <div >
        <div className="loginBg ">
          {/* <img className="logo_2" src="./assets/images/logo_touming.png" alt="" /> */}
          <img className="logo_2" src={require('../../resource/assets/images/logo_touming.png')} alt="" />
        </div>
        <div className="loginRight">
          <div className="title">保险业务核心系统
            <div className="blueLine"></div>
          </div>
          <div className="userForm" style={{width: '60%'}}>
            <Form layout="inline">
              <Row style={rowStyle} >
                <Col span="16">
                  <FormItem >
                    {
                      getFieldDecorator('loginName', {
                        initialValue: this.state.userInfo.remberUserName ? this.state.userInfo.loginName : '',
                        rules: [{ validator: this.validLoginName }]
                      })(
                        <Input id="input" onKeyUp={(e) => { this.filterSpace(e, 'loginName') }} style={inputStyle} prefix={<Icon type="user" style={iconStyle} />} onFocus={this.onfocus} placeholder="请输入账户名" />
                      )
                    }

                  </FormItem>
                </Col>
                <div className="inputline"></div>
              </Row>
              <Row style={rowStyle}>
                <FormItem >

                  {
                    getFieldDecorator('password', {
                      initialValue: this.state.userInfo.remberPwd ? this.state.userInfo.password : '',
                      rules: []
                    })(
                      <Input type="password" onKeyUp={(e) => { this.filterSpace(e, 'password') }} prefix={<Icon type="lock" style={iconStyle} />} onFocus={this.onfocus} placeholder="请输入账户密码" />
                    )
                  }
                </FormItem>
                <div className="inputline"></div>

              </Row>
              <Row style={{...rowStyle,...this.state.imgCodeShow}}>
                <Col span="16">
                  <FormItem >
                    {
                      getFieldDecorator('code', {
                        rules: [
                          { require: true }
                        ]
                      })(
                        <Input onKeyUp={(e) => { this.filterSpace(e, 'code') }} onPressEnter={this.submit} minLength={4} prefix={<Icon type="safety" style={iconStyle} />} onFocus={this.onfocus} placeholder="请输入验证码" />
                      )
                    }
                  </FormItem>
                  <div className="inputline"></div>
                </Col>
                <Col span="4">
                  <div onClick={this.getImgCode} className="ideCode">
                    {this.state.imgCode ? <img width={'100%'} height={'100%'} src={'data:image/png;base64,' + this.state.imgCode} alt="imgcode" /> : '获取验证码'}
                  </div>
                </Col>
              </Row>
              <Row style={rowStyle}>
                <Col span="12">
                  <FormItem >
                    {
                      getFieldDecorator('remberUserName', {
                        valuePropName: 'checked',
                        initialValue: this.state.userInfo.remberUserName ? true : false
                      })(
                        <Checkbox  >记住账户</Checkbox>
                      )
                    }
                  </FormItem>
                </Col>
                <Col span="12">
                  <FormItem >
                    {
                      getFieldDecorator('remberPwd', {
                        valuePropName: 'checked',
                        initialValue: this.state.userInfo.remberPwd ? true : false
                      })(

                        <Checkbox  >记住密码</Checkbox>
                      )
                    }
                  </FormItem>
                </Col>
              </Row>
              <Row>
                <div className={{ display: showError ? 'block' : 'none' }} style={{ ...rowStyle, color: 'red' }}>{tips}</div>
              </Row>
              <Row style={rowStyle}>
                <Col span="24">
                  <Button className="loginBtn" onClick={this.submit} type="primary">登录</Button>
                </Col>
              </Row>
            </Form>
          </div>
        </div>
      </div>
    )
  }
}
export default withRouter(Form.create()(Login));