刘光辉
11 小时以前 0dfe84494048ce27ba8449831782128412d3eb13
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
<script lang="ts" setup>
import { nextTick, onMounted, onUnmounted, reactive, ref, toRefs } from 'vue';
import { useRoute } from 'vue-router';
 
import { useGlobSetting, useMessage } from '@jnpf/hooks';
import { ScrollContainer } from '@jnpf/ui';
import { BasicModal, useModal } from '@jnpf/ui/modal';
import { AesEncryption, encryptByMd5 } from '@jnpf/utils';
 
import { useAccessStore } from '@vben/stores';
 
import { StorageManager } from '@vben-core/shared/cache';
 
import { ArrowRightOutlined, LeftOutlined } from '@ant-design/icons-vue';
import { onKeyStroke } from '@vueuse/core';
import { Button, Form, Input } from 'ant-design-vue';
 
import { saasLoginApi } from '#/api';
import { getConfig, getLoginConfig, getTicket, getTicketStatus, socialsLogin } from '#/api/core/user';
import { vDisablePasswordAutofill } from '#/directives/disablePasswordAutofill';
import { $t } from '#/locales';
import { useAuthStore } from '#/store';
 
import ApplyTenantModal from './ApplyTenantModal.vue';
import QrCodeForm from './QrCodeForm.vue';
import { useFormRules, useFormValid } from './useLogin';
 
interface State {
  formData: any;
  isSso: boolean;
  ssoLoading: boolean;
  preUrl: string;
  ssoUrl: string;
  ssoTicket: string;
  ticketParams: string;
  socialsList: any[];
  socialsWinUrl: any;
  redirectUrl: string;
  ssoTimer: any;
  tenantSocialList: any[];
  showIframe: boolean;
  needCode: boolean;
  codeLength: number;
  timestamp: number;
  codeImgUrl: string;
  activeTab: number;
  redirect: string;
  companyList: any[];
  accessToken: string;
  isSaas: boolean;
}
const emit = defineEmits(['changeLoading']);
 
const FormItem = Form.Item;
const InputPassword = Input.Password;
const { createInfoModal, createMessage, notification } = useMessage();
const authStore = useAuthStore();
const accessStore = useAccessStore();
const ls = new StorageManager();
const route = useRoute();
const query = route.query;
const globSetting = useGlobSetting();
const apiUrl = ref(globSetting.apiURL);
const [registerSsoModal, { openModal: openSsoModal, closeModal: closeSsoModal }] = useModal();
const [registerTenantSocialModal, { openModal: openTenantSocialModal }] = useModal();
const [registerApplyTenantModal, { openModal: openApplyTenantModal }] = useModal();
const { getFormRules } = useFormRules();
 
const formRef = ref();
const loading = ref(false);
const aesEncryption = new AesEncryption({ useHex: true });
 
let socialsWinUrl: any = null;
const state = reactive<State>({
  formData: {
    account: '',
    password: '',
    code: '',
    origin: 'password',
  },
  isSso: false,
  ssoLoading: true,
  preUrl: '',
  ssoUrl: '',
  ssoTicket: '',
  ticketParams: '',
  socialsList: [],
  socialsWinUrl: null,
  redirectUrl: '',
  ssoTimer: null,
  tenantSocialList: [],
  showIframe: false,
  needCode: false,
  codeLength: 4,
  timestamp: 0,
  codeImgUrl: '',
  activeTab: 1,
  redirect: '',
  companyList: [],
  accessToken: '', // 临时授权token
  isSaas: false,
});
const { formData, socialsList, isSso, ssoLoading, ssoUrl, showIframe, tenantSocialList, codeImgUrl, activeTab, companyList, isSaas } = toRefs(state);
const { validForm } = useFormValid(formRef);
 
onKeyStroke('Enter', () => {
  if (state.activeTab !== 1) return;
  handleLogin();
});
 
async function handleLogin() {
  if (loading.value) return;
  const data = await validForm();
  if (!data) return;
  try {
    loading.value = true;
    const password = encryptByMd5(data.password);
    const encryptPassword = aesEncryption.encryptByAES(password);
    const userInfo = await authStore.authLogin({
      account: data.account,
      password: encryptPassword,
      code: state.formData.code,
      origin: state.formData.origin,
      timestamp: state.timestamp,
      jnpf_ticket: state.ssoTicket,
      grant_type: 'password',
    });
 
    if (userInfo) {
      if ((userInfo as any).saasList?.length) {
        state.companyList = (userInfo as any).saasList;
        state.accessToken = (userInfo as any).accessToken;
        state.activeTab = 3;
        return;
      }
    } else {
      if (state.needCode) {
        state.formData.code = '';
        handleChangeImg();
      }
      loading.value = false;
      return;
    }
 
    await authStore.redirectAfterLogin(state.redirect);
  } catch {
    if (state.needCode) {
      state.formData.code = '';
      handleChangeImg();
    }
    loading.value = false;
  }
}
function handleGetLoginConfig() {
  state.ssoLoading = true;
  getLoginConfig()
    .then((res) => {
      state.isSso = !!res.data.redirect;
      state.preUrl = res.data.url;
      state.ticketParams = res.data.ticketParams;
      state.socialsList = res.data.socialsList || [];
      state.ssoLoading = false;
      state.isSaas = res.data.isSaas || false;
      ls.setItem('useSocials', state.socialsList.length);
      if (!res.data.message) return;
      notification.open({
        message: $t('common.tipTitle'),
        description: res.data.message,
        style: { width: '300px' },
        duration: 0,
      });
    })
    .catch(() => {
      state.isSso = false;
      state.ssoLoading = false;
    });
}
function handleOtherLogin(enname) {
  getTicket().then((res) => {
    state.ssoTicket = res.data;
    if (socialsWinUrl && !socialsWinUrl.closed) {
      socialsWinUrl.location.replace(state.redirectUrl);
      socialsWinUrl.focus();
      return;
    }
    state.socialsList.forEach((item) => {
      if (enname == item.enname) {
        const renderUrl = item.renderUrl.replace('JNPF_TICKET', state.ssoTicket);
        state.redirectUrl = renderUrl;
      }
    });
    const iWidth = 750; // 弹出窗口的宽度;
    const iHeight = 700; // 弹出窗口的高度;
    const iLeft = (window.screen.width - iWidth) / 2;
    const iTop = (window.screen.height - iHeight) / 2; // 获得窗口的垂直位置;
    socialsWinUrl = window.open(
      state.redirectUrl,
      '_blank',
      `height=${iHeight},innerHeight=${iHeight},width=${iWidth},innerWidth=${iWidth},top=${iTop},left=${iLeft},toolbar=no,menubar=no,scrollbars=auto,resizeable=no,location=no,status=no`,
    );
    state.ssoTimer = setInterval(() => {
      if (socialsWinUrl.closed) clearTimer();
      handleGetTicketStatus();
    }, 1000);
  });
}
function clearTimer() {
  if (!state.ssoTimer) return;
  clearInterval(state.ssoTimer);
  state.ssoTimer = null;
  state.ssoTicket = '';
}
function handleGetTicketStatus() {
  if (!state.ssoTicket) return;
  getTicketStatus(state.ssoTicket).then((res) => {
    if (res.data.status != 2) {
      socialsWinUrl && socialsWinUrl.close();
      if (res.data.status == 4 || res.data.status == 6) {
        // 未绑定预留ticket
        clearInterval(state.ssoTimer);
        state.ssoTimer = null;
      } else {
        clearTimer();
      }
      switch (res.data.status) {
        case 1: {
          // 登陆成功
          accessStore.setAccessToken(res.data.value);
          nextTick(() => authStore.redirectAfterLogin(state.redirect));
          break;
        }
        case 4: {
          // 未绑定
          createMessage.error('第三方账号未绑定,5分钟内登录本系统账号密码自动绑定该账号!');
          closeSsoModal();
          state.ssoUrl = '';
          break;
        }
        case 6: {
          // 多租户绑定多个
          state.tenantSocialList = typeof res.data.value === 'string' ? JSON.parse(res.data.value) : res.data.value;
          openTenantSocialModal(true);
          break;
        }
        case 7: {
          // 免登
          createMessage.error('第三方账号未绑定账号,请绑定后重试!');
          break;
        }
        default: {
          createMessage.error(res.data.value || '账号异常!');
          closeSsoModal();
          state.ssoUrl = '';
          getLoginConfig();
          break;
        }
      }
    }
  });
}
function handleSsoLogin() {
  if (loading.value) return;
  loading.value = true;
  getTicket().then((res) => {
    state.ssoTicket = res.data;
    state.ssoUrl = `${state.preUrl}?${state.ticketParams}=${state.ssoTicket}`;
    openSsoModal(true);
    state.showIframe = true;
    state.ssoTimer = setInterval(() => {
      handleGetTicketStatus();
    }, 1000);
  });
}
async function onSsoModalClose() {
  loading.value = false;
  state.showIframe = false;
  clearTimer();
  return true;
}
function handleSocialLogin(data) {
  socialsLogin({ ...data, jnpf_ticket: state.ssoTicket, tenantLogin: true }).then((res) => {
    accessStore.setAccessToken(res.data.token);
    nextTick(() => authStore.redirectAfterLogin(state.redirect));
  });
}
function onAccountChange(e) {
  const value = e.target.value;
  if (!value) return;
  handleGetConfig(value);
}
function handleGetConfig(value) {
  getConfig(value).then((res) => {
    state.needCode = !!res.data.enableVerificationCode;
    if (state.needCode) {
      state.codeLength = res.data.verificationCodeNumber || 4;
      handleChangeImg();
    }
  });
}
function handleChangeImg() {
  const timestamp = Math.random();
  state.timestamp = timestamp;
  state.codeImgUrl = `/api/oauth/ImageCode/${state.codeLength || 4}/${timestamp}`;
}
function handleCompanySelect(item) {
  emit('changeLoading', true);
  const query = { account: item.account, tenantId: item.tenantId, accessToken: state.accessToken };
  saasLoginApi(query)
    .then((res) => {
      accessStore.setAccessToken(res.data.token);
      nextTick(() => authStore.redirectAfterLogin(state.redirect));
    })
    .catch(() => {
      emit('changeLoading', false);
    });
}
function handleApplyTenant() {
  openApplyTenantModal(true, {});
}
function backToLogin() {
  loading.value = false;
  state.activeTab = 1;
}
function handleForgetPassword() {
  createInfoModal({
    title: $t('common.tipTitle'),
    content: $t('sys.login.forgetPasswordTip'),
  });
}
 
onMounted(() => {
  if (state.formData.account) handleGetConfig(state.formData.account);
  if (state.needCode) handleChangeImg();
  state.redirect = query?.redirect ? decodeURIComponent(query?.redirect as string) : '';
  if (query?.JNPF_TICKET) {
    state.ssoTicket = query.JNPF_TICKET as string;
    handleGetTicketStatus();
  }
  handleGetLoginConfig();
});
onUnmounted(() => {
  clearTimer();
});
</script>
<template>
  <div class="company-container enter-x" v-if="activeTab == 3">
    <div class="company-container-back" @click="backToLogin"><LeftOutlined />{{ $t('common.back') }}</div>
    <div class="px-[20px]">
      <div class="company-container-cap">请选择您已加入的企业</div>
      <div class="company-container-list">
        <ScrollContainer>
          <div class="company-item" v-for="(item, index) in companyList" :key="index" @click="handleCompanySelect(item)">
            <div class="company-item-icon">{{ item.companyName ? item.companyName[0] : '' }}</div>
            <p class="company-item-name" :title="item.companyName">{{ item.companyName }}</p>
            <ArrowRightOutlined />
          </div>
        </ScrollContainer>
      </div>
    </div>
  </div>
  <template v-else>
    <div class="login-title">
      <div class="login-cap">欢迎登录</div>
      <div class="login-sub-title">实验室管理平台</div>
    </div>
    <div v-show="!isSso && !ssoLoading">
      <Form autocomplete="off" class="enter-x" :model="formData" :rules="getFormRules" ref="formRef" v-show="activeTab == 1">
        <FormItem name="account" class="enter-x">
          <Input size="large" v-model:value="formData.account" :placeholder="$t('sys.login.username')" class="fix-auto-fill" @blur="onAccountChange" />
        </FormItem>
        <FormItem name="password" class="enter-x">
          <InputPassword v-disable-password-autofill size="large" v-model:value="formData.password" :placeholder="$t('sys.login.password')" />
        </FormItem>
        <FormItem name="code" class="enter-x" v-if="state.needCode">
          <a-row type="flex" justify="space-between">
            <a-col class="sms-input">
              <a-input v-model:value="formData.code" :placeholder="$t('sys.login.codeTip')" name="code" size="large" />
            </a-col>
            <a-col class="sms-right">
              <a-tooltip :content="$t('sys.login.changeCode')" placement="bottom">
                <img class="codeImg" :alt="$t('sys.login.changeCode')" :src="apiUrl + codeImgUrl" @click="handleChangeImg" />
              </a-tooltip>
            </a-col>
          </a-row>
        </FormItem>
        <div class="pt-[10px]">
          <FormItem class="enter-x">
            <Button type="primary" size="large" block @click="handleLogin" :loading="loading">
              {{ $t('sys.login.loginButton') }}
            </Button>
          </FormItem>
        </div>
        <div class="enter-x mt-[-10px] pb-[10px] text-center">
          <span class="link-text" @click="handleForgetPassword">{{ $t('sys.login.forgetPassword') }}</span>
        </div>
        <div class="mt-[-20px] pt-[10px]" v-if="isSaas">
          <FormItem class="enter-x">没有企业?<span class="link-text" @click="handleApplyTenant">免费申请</span></FormItem>
        </div>
      </Form>
      <QrCodeForm v-if="activeTab == 2" />
      <div class="socials-box" v-if="activeTab == 1 && socialsList.length">
        <a-divider>{{ $t('sys.login.otherLogin') }}</a-divider>
        <div class="socials-list">
          <a-tooltip :title="`${item.name}登录`" v-for="(item, i) in socialsList" :key="i">
            <div class="socials-item" @click="handleOtherLogin(item.enname)"><i :class="item.icon"></i></div>
          </a-tooltip>
        </div>
      </div>
    </div>
    <a-button type="primary" class="sso-login-btn enter-x" size="large" :loading="loading" @click="handleSsoLogin" v-show="isSso && !ssoLoading">登录</a-button>
  </template>
 
  <BasicModal v-bind="$attrs" @register="registerSsoModal" title="登录" :footer="null" :width="1000" class="jnpf-sso-modal" :close-func="onSsoModalClose">
    <iframe width="100%" height="100%" :src="ssoUrl" frameborder="0" v-if="showIframe"></iframe>
  </BasicModal>
  <BasicModal
    v-bind="$attrs"
    @register="registerTenantSocialModal"
    :closable="false"
    :footer="null"
    :width="700"
    class="jnpf-tenant-social-modal"
    destroy-on-close>
    <div class="other-main">
      <div class="other-title">
        <div class="other-icon"><i class="icon-ym icon-ym-user"></i></div>
        <div class="other-text">请选择登录账号</div>
      </div>
      <div class="other-body">
        <a-row :gutter="20">
          <a-col :span="12" v-for="(item, i) in tenantSocialList" :key="i">
            <div @click="handleSocialLogin(item)">
              <a-card hoverable class="other-login-card">
                <div class="other-login-des other-login-title">{{ item.socialName }}</div>
                <div class="other-login-des">租户名称:{{ item.tenantName }}</div>
                <div class="other-login-des">租户ID:{{ item.tenantId }}</div>
                <div class="other-login-des">账号ID:{{ item.accountName }}</div>
              </a-card>
            </div>
          </a-col>
        </a-row>
      </div>
    </div>
  </BasicModal>
  <ApplyTenantModal @register="registerApplyTenantModal" />
</template>