king
2021-08-11 a757b75163d77acc5111637fbe20ec61d895a72b
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
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
import React, { Component } from 'react'
import { message, Modal } from 'antd'
import { connect } from 'react-redux'
import md5 from 'md5'
import moment from 'moment'
 
import Api from '@/api'
import Utils from '@/utils/utils.js' 
import options, { styles } from '@/store/options.js'
import zhCN from '@/locales/zh-CN/login.js'
import enUS from '@/locales/en-US/login.js'
import asyncLoadComponent from '@/utils/asyncLoadComponent'
import { modifyMemberLevel } from '@/store/action'
import './index.scss'
 
const LoginForm = asyncLoadComponent(() => import('./loginform'))
const LoginCloudForm = asyncLoadComponent(() => import('./logincloudform'))
const iszhCN = sessionStorage.getItem('lang') !== 'en-US'
 
const _href = window.location.href.split('#')[0]
if (localStorage.getItem(_href + 'paramsmain')) {
  sessionStorage.setItem('history', localStorage.getItem(_href + 'paramsmain'))
  localStorage.removeItem(_href + 'paramsmain')
}
 
class Login extends Component {
  state = {
    selectedlang: iszhCN ? 'zh-CN' : 'en-US',
    dict: iszhCN ? zhCN : enUS,
    isDisabled: false,
    auth: false,
    authError: '',
    loginlogo: window.GLOB.loginlogo || '',
    bgImage: window.GLOB.bgImage || '',
    platName: window.GLOB.platName || '',
    copyRight: window.GLOB.copyRight || '',
    ICP: window.GLOB.ICP || '',
    lineColor: window.GLOB.lineColor || '',
    webSite: window.GLOB.webSite || '',
    langList: [],
    syncApp: false,
    loginWays: null,
    touristLogin: false,
    syncing: false,
    ipAddress: '',
    city: ''
  }
 
  changelang (item) {
    // 切换语言
    this.setState({
      dict: item === 'zh-CN' ? zhCN : enUS
    })
  }
 
  handleSubmit = () => {
    this.loginformRef.handleConfirm().then(res => {
      this.setState({
        isDisabled: true
      })
 
      if (res.type === 'uname_pwd') {
        this.loginsubmit(res)
      } else if (res.type === 'sms_vcode') {
        this.phoneloginsubmit(res)
      }
    })
  }
 
  /**
   * @description 账号密码登录
   * @param {Object} param 用户名密码等信息
   */
  async loginsubmit (param) {
    const { ipAddress, city } = this.state
    if (options.sysType === 'local' && !window.GLOB.mainSystemApi) { // 业务系统必须设置单点地址
      Modal.warning({
        title: '未设置单点服务器地址,请联系管理员!'
      })
      return
    }
 
    // 登录提交
    let res = await Api.getusermsg(param.username, param.password, false, ipAddress, city)
    if (res.status) {
      sessionStorage.setItem('UserID', res.UserID)
      sessionStorage.setItem('LoginUID', res.LoginUID)
      sessionStorage.setItem('User_Name', res.UserName)
      sessionStorage.setItem('Full_Name', res.FullName)
      sessionStorage.setItem('avatar', res.icon || '')
      sessionStorage.setItem('dataM', res.dataM ? 'true' : '')
      sessionStorage.setItem('localDataM', res.dataM ? 'true' : '')
      sessionStorage.setItem('debug', res.debug || '')
      sessionStorage.setItem('role_id', res.role_id || '')
      sessionStorage.setItem('localRole_id', res.role_id || '')
      
      let _url = window.location.href.split('#')[0]
 
      localStorage.setItem(_url + 'lang', param.lang || 'zh-CN')
      sessionStorage.setItem('lang', param.lang || 'zh-CN')
 
      sessionStorage.removeItem('visitorUserID')
      sessionStorage.removeItem('visitorLoginUID')
      
      if (param.remember) { // 记住密码时账号密码存入localStorage
        localStorage.setItem(_url, window.btoa(window.encodeURIComponent(JSON.stringify({username: param.username, password: param.password}))))
      } else {
        localStorage.removeItem(_url)
      }
 
      let _history = sessionStorage.getItem('history')
      if (_history) {
        sessionStorage.removeItem('history')
        // 查看是否为其他页面跳转,路径存在时,跳回原页面
        this.props.history.replace(_history)
      } else {
        this.props.history.replace('/main')
      }
    } else if (res.ErrCode === 'Need_Get_Appkey' && options.sysType === 'SSO') {
      message.warning('应用尚未创建,请向云端同步应用!')
 
      this.setState({
        isDisabled: false,
        syncApp: true
      })
    } else {
      message.warning(res.message)
      if (res.message.indexOf('密码错误') > -1) {
        const input = document.getElementById('password')
        if (input) {
          input.select()
        }
      } else if (res.message.indexOf('登录权限') > -1) {
        const input = document.getElementById('username')
        if (input) {
          input.select()
        }
      }
      this.setState({
        isDisabled: false
      })
    }
  }
 
  async phoneloginsubmit (param) {
    const { ipAddress, city } = this.state
    if (options.sysType === 'local' && !window.GLOB.mainSystemApi) { // 业务系统必须设置单点地址
      Modal.warning({
        title: '未设置单点服务器地址,请联系管理员!'
      })
      return
    }
 
    // 登录提交
    let res = await Api.getphoneusermsg(param.phone, param.vercode, false, ipAddress, city)
    if (res.status) {
      sessionStorage.setItem('UserID', res.UserID)
      sessionStorage.setItem('LoginUID', res.LoginUID)
      sessionStorage.setItem('User_Name', res.UserName)
      sessionStorage.setItem('Full_Name', res.FullName)
      sessionStorage.setItem('avatar', res.icon || '')
      sessionStorage.setItem('dataM', res.dataM ? 'true' : '')
      sessionStorage.setItem('localDataM', res.dataM ? 'true' : '')
      sessionStorage.setItem('debug', res.debug || '')
      sessionStorage.setItem('role_id', res.role_id || '')
      sessionStorage.setItem('localRole_id', res.role_id || '')
 
      let _url = window.location.href.split('#')[0]
 
      localStorage.setItem(_url + 'lang', param.lang || 'zh-CN')
      sessionStorage.setItem('lang', param.lang || 'zh-CN')
 
      sessionStorage.removeItem('visitorUserID')
      sessionStorage.removeItem('visitorLoginUID')
 
      let _history = sessionStorage.getItem('history')
      if (_history) {
        sessionStorage.removeItem('history')
        // 查看是否为其他页面跳转,路径存在时,跳回原页面
        this.props.history.replace(_history)
      } else {
        this.props.history.replace('/main')
      }
    } else if (res.ErrCode === 'Need_Get_Appkey' && options.sysType === 'SSO') {
      message.warning('应用尚未创建,请向云端同步应用!')
 
      this.setState({
        isDisabled: false,
        syncApp: true
      })
    } else {
      message.warning(res.message)
      this.setState({
        isDisabled: false
      })
    }
  }
 
  componentDidMount () {
    // 获取ip及城市信息
    let ipurl = window.atob('aHR0cHM6Ly9lcGMubWs5a$mkC5jbi93ZWJhcGkvaXBsb2M='.replace(/\$mk/ig, ''))
    Api.directRequest(ipurl, 'get', null, 'true').then(res => {
      if (!res || !res.location) return
      sessionStorage.setItem('city', res.location)
      this.setState({
        ipAddress: res.ip || '',
        city: res.location
      })
    })
    const timeStamp = new Date().getTime()
    const _authUrl = window.location.href.split('#')[0] + 'AuthCode'
 
    let authCode = localStorage.getItem(_authUrl)
    let _s = md5('mksoft' + moment().format('YYYYMMDD'))
    authCode = authCode ? authCode.split(',') : []
    let index = authCode.findIndex(key => key === _s)
 
    if (index > -1) {
      this.setState({
        auth: true
      })
    }
 
    if (index === -1 || index > 5) {
      let _appId = window.GLOB.appId
  
      if (options.sysType === 'cloud') { // 云端使用系统配置appid
        _appId = options.caId
      }
  
      let str = md5('MK19' + _appId + timeStamp)
      let _rduri = window.atob('aHR0cHM6Ly9lcGMubWs5aC5$mkjbi93ZWJhcGkvZG9zdGFycw=='.replace(/\$mk/ig, ''))
      let _func = window.atob('c0VtcG93ZXJDbG91$mkZF9HZXRfTGlua1VybA=='.replace(/\$mk/ig, ''))
      let _id = window.atob('YmgwYmFwYWJ0ZDQ1ZXBz$mkZ3JhNzlzZWdiY2g2YzFpYms='.replace(/\$mk/ig, ''))
  
      let param = {
        func: _func,
        AppID: _appId,
        TimeStamp: timeStamp,
        appkey: window.GLOB.appkey,
        userid: _id,
        LoginUID: _id,
        nonc: Utils.getuuid()
      }
 
      // param = {
      //   func: _func,
      //   VerificationCode: '授权码',
      //   TimeStamp: timeStamp,
      //   userid: _id,
      //   LoginUID: _id,
      //   nonc: Utils.getuuid()
      // }
 
      let keys = Object.keys(param).sort()
      let values = ''
      keys.forEach(key => {
        values += key + param[key]
      })
      param.sign = md5(values)
      param.t = new Date().getTime()
  
      Api.directRequest(_rduri + '/' + _func, 'post', param, 'true').then(res => {
        if (res.status) {
          if (res.EPC === str) {
            let box = []
            for (let i = 0; i < 15; i++) {
              let s = 'mksoft' + moment().add(i, 'days').format('YYYYMMDD')
              box.push(md5(s))
            }
            box = box.join(',')
            localStorage.setItem(_authUrl, box)
    
            this.setState({
              auth: true
            })
          } else {
            localStorage.removeItem(_authUrl)
            this.setState({
              auth: false
            })
          }
        } else if (res.ErrCode === 'N') {
          localStorage.removeItem(_authUrl)
          this.setState({
            auth: false,
            authError: res.message
          })
        }
      })
    }
 
    Api.getTouristMsg().then(result => {
      if (result.status) {
        sessionStorage.setItem('visitorUserID', result.UserID || '')
        sessionStorage.setItem('visitorLoginUID', result.LoginUID || '')
 
        if (result.UserID && result.LoginUID) {
          this.setState({touristLogin: true})
        }
 
        // 获取系统信息
        let _param = {
          func: 's_Get_style',
          TypeCharOne: 'PC',
          LText: `select '${window.GLOB.appkey}'`,
        }
 
        _param.userid = result.UserID
        _param.LoginUID = result.LoginUID
        _param.timestamp = moment().format('YYYY-MM-DD HH:mm:ss')
        _param.secretkey = Utils.encrypt(_param.LText, _param.timestamp)
 
        Api.getSystemConfig(_param).then(res => {
          if (res.status) {
            // positecgroup
            // res.Banner = res.Banner ? res.Banner.replace(/:8080/ig, '').replace(/http:/ig, 'https:') : ''
            // res.doclogo = res.doclogo ? res.doclogo.replace(/:8080/ig, '').replace(/http:/ig, 'https:') : ''
            // res.indexlogo = res.indexlogo ? res.indexlogo.replace(/:8080/ig, '').replace(/http:/ig, 'https:') : ''
            // res.loginlogo = res.loginlogo ? res.loginlogo.replace(/:8080/ig, '').replace(/http:/ig, 'https:') : ''
 
            let _url = window.location.href.split('#')[0] + 'system'
            let systemMsg = {
              favicon: res.titlelogo || '',
              platTitle: res.titleName || '',
              platName: res.SysName || '',
              bgImage: res.Banner || '',
              loginlogo: res.loginlogo || '',
              copyRight: res.CopyRightYear && res.CopyRightOrg ? `Copyright©${res.CopyRightYear}    所有相关版权归    ${res.CopyRightOrg}` : '',
              ICP: res.ICP || '',
              mainlogo: res.indexlogo || '',
              doclogo: res.doclogo || '',
              style: res.CSS || '',
              showline: res.split_line_show || 'true',
              webSite: res.WebSite || '',
              navBar: res.menu_type
            }
 
            sessionStorage.setItem('home_background', res.index_background_color || '')
            if (res.sys_datetime) {
              sessionStorage.setItem('sys_datetime', res.sys_datetime)
              sessionStorage.setItem('app_datetime', new Date().getTime())
            }
 
            // url标题
            document.title = systemMsg.platTitle
 
            try {
              localStorage.setItem(_url, window.btoa(window.encodeURIComponent(JSON.stringify(systemMsg))))
            } catch {
              localStorage.removeItem(_url)
            }
 
            let _loginurl = window.location.href.split('#')[0] + 'loginways'
            let login_ways = []
            let login_types = []
            if (res.login_ways && res.login_ways.length > 0) {
              res.login_ways.forEach(item => {
                // 短信验证码登录,必须设置短信Id
                if (item.way_no === 'sms_vcode' && !item.sms_id) return
                if (login_types.includes(item.way_no)) return
 
                login_types.push(item.way_no)
 
                login_ways.push({
                  label: item.way_name,
                  type: item.way_no,
                  smsId: item.sms_id
                }) 
              })
            } else {
              login_ways.push({
                label: '账号密码登录',
                type: 'uname_pwd',
                smsId: ''
              })
            }
 
            try {
              localStorage.setItem(_loginurl, window.btoa(window.encodeURIComponent(JSON.stringify(login_ways))))
            } catch {
              localStorage.removeItem(_loginurl)
            }
            
            this.setState({
              loginWays: login_ways,
              langList: res.lang_data || [],
              ...systemMsg
            })
 
            window.GLOB.mainlogo = systemMsg.mainlogo
            window.GLOB.style = systemMsg.style
            window.GLOB.navBar = systemMsg.navBar
        
            if (window.GLOB.style && styles[window.GLOB.style]) {
              document.body.className = styles[window.GLOB.style] + ' ' + (res.split_line_show === 'false' ? 'hidden-split-line' : '')
            }
 
            if (res.titlelogo && window.GLOB.favicon !== res.titlelogo) {
              let link = document.querySelector("link[rel*='icon']") || document.createElement('link')
              link.type = 'image/x-icon'
              link.rel = 'shortcut icon'
              link.href = res.titlelogo
              document.getElementsByTagName('head')[0].appendChild(link)
            }
 
            let memberLevel = res.member_level
 
            if (typeof(memberLevel) === 'number' && memberLevel > 10 && parseInt(memberLevel / 10) * 10 === memberLevel) {
              sessionStorage.setItem('Member_Level', md5('mksoft' + moment().format('YYYYMM') + memberLevel))
              this.props.modifyMemberLevel(memberLevel)
            }
 
            if (res.users_upt === 'true' && window.GLOB.systemType === 'production') {
              Api.getLocalConfig ({
                func: 's_Get_local_u_deleted',
                users_upt_date: res.users_upt_date,
                userid: result.UserID,
                LoginUID: result.LoginUID
              }).then(localres => {
                if (!localres.status) return
                Api.getSystemConfig({
                  func: 's_get_sso_u_create',
                  user_ids: localres.user_ids,
                  user_ids_local: localres.user_ids_local,
                  users_upt_date: localres.users_upt_date,
                  userid: result.UserID,
                  LoginUID: result.LoginUID
                }).then(ssores => {
                  if (!ssores.status) return
                  Api.getLocalConfig ({
                    func: 's_get_local_u_create',
                    user_ids_local: ssores.user_ids_local,
                    userid: result.UserID,
                    LoginUID: result.LoginUID
                  })
                })
              })
            }
          } else {
            message.warning(res.message)
          }
        })
      } else {
        message.warning(result.message)
      }
    })
    
    let loginWays = localStorage.getItem(window.location.href.split('#')[0] + 'loginways')
    if (loginWays) {
      try {
        loginWays = JSON.parse(window.decodeURIComponent(window.atob(loginWays)))
      } catch {
        localStorage.removeItem(window.location.href.split('#')[0] + 'loginways')
      }
 
      if (loginWays) {
        this.setState({
          loginWays: loginWays
        })
      }
    }
  }
 
  syncSubmit = () => {
    this.setState({
      syncing: true
    })
 
    let param = {
      func: 's_get_app_from_cloud',
      UserName: '',
      Password: '',
      systemType: options.sysType,
      Type: 'X',
      debug: 'Y'
    }
 
    param.appkey = window.GLOB.appkey || ''
 
    if (options.cloudServiceApi) {
      param.rduri = options.cloudServiceApi.replace('dostars', 'dostar')
    }
 
 
    this.logincloudRef.handleConfirm().then(result => {
      param.UserName = result.cloudusername
      param.Password = result.cloudpassword
 
      param.Password = Utils.formatOptions(param.Password)
 
      Api.dostarInterface(param).then(res => {
        if (res.status) {
          let _param = {
            func: 's_sDataDictb_TBBack',
            LTextOut: res.LTextOut,
            lid: res.Lid,
            Appkey: window.GLOB.appkey || ''
          }
 
          _param.timestamp = moment().format('YYYY-MM-DD HH:mm:ss')
          _param.secretkey = Utils.encrypt(_param.LTextOut, _param.timestamp)
          _param.open_key = Utils.encryptOpenKey(_param.secretkey, _param.timestamp)
 
          Api.dostarInterface(_param).then(response => {
            if (response.status) {
              message.success('应用创建成功。')
              this.setState({
                syncing: false,
                syncApp: false
              })
            } else {
              this.setState({
                syncing: false
              })
              message.warning(response.message)
            }
          })
 
        } else {
          this.setState({
            syncing: false
          })
          message.warning(res.message)
        }
      })
    })
  }
 
  /**
   * @description 组件销毁,清除state更新
   */
  componentWillUnmount () {
    this.setState = () => {
      return
    }
  }
 
  render () {
    const { lineColor, bgImage, loginlogo, copyRight, webSite, ICP, loginWays, touristLogin } = this.state
 
    return (
      <div className="login-container" style={bgImage ? {backgroundImage: 'url(' + bgImage + ')'} : {}}>
        <div className="logo" style={lineColor ? {borderColor: lineColor} : {}}>
          {loginlogo ? <img src={loginlogo} alt=""/> : null}
          {this.state.platName ? <p className="plat-name">{this.state.platName}</p> : null}
        </div>
        <div className="login-middle" style={lineColor ? {borderColor: lineColor} : {}}>
          {loginWays ? <LoginForm
            platName={this.state.platName}
            dict={this.state.dict}
            auth={this.state.auth}
            authError={this.state.authError}
            touristLogin={touristLogin}
            loginWays={loginWays}
            lang={this.state.selectedlang}
            langList={this.state.langList}
            isDisabled={this.state.isDisabled}
            changelang={(value) => this.changelang(value)}
            handleSubmit={() => this.handleSubmit()}
            wrappedComponentRef={(inst) => this.loginformRef = inst}
          /> : null}
        </div>
        <div className="login-bottom">
          {webSite && copyRight ?
            <a target="_blank" rel="noopener noreferrer" href={webSite} dangerouslySetInnerHTML={{ __html: copyRight.replace(/\s/ig, '&nbsp;') }}></a> :
            <p dangerouslySetInnerHTML={{ __html: copyRight ? copyRight.replace(/\s/ig, '&nbsp;') : '' }}></p>
          }
          {ICP ? <p dangerouslySetInnerHTML={{ __html: ICP.replace(/\s/ig, '&nbsp;') }}></p> : null}
        </div>
        {/* 编辑状态登录 */}
        <Modal
          title={this.state.dict['login.sync.cloud']}
          okText={this.state.dict['login.ok']}
          cancelText={this.state.dict['login.cancel']}
          visible={this.state.syncApp}
          onOk={this.syncSubmit}
          maskClosable={false}
          className="sync-cloud-application"
          width={'430px'}
          confirmLoading={this.state.syncing}
          onCancel={() => {this.setState({ syncApp: false, syncing: false })}}
          destroyOnClose
        >
          <LoginCloudForm handleSubmit={() => this.syncSubmit()} wrappedComponentRef={(inst) => this.logincloudRef = inst}/>
        </Modal>
      </div>
    )
  }
}
 
const mapStateToProps = () => {
  return {}
}
 
const mapDispatchToProps = (dispatch) => {
  return {
    modifyMemberLevel: (memberLevel) => dispatch(modifyMemberLevel(memberLevel))
  }
}
 
export default connect(mapStateToProps, mapDispatchToProps)(Login)