-
zhangwei
昨天 2f5177b8a553bdc468cc68a20029916f59d1b4f1
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
<template>
    <el-tooltip :visible="state.capsLockVisible" effect="light" :content="$t('message.account.placeholder5')" placement="top">
        <el-form ref="ruleFormRef" :model="state.ruleForm" size="large" :rules="state.rules" class="login-content-form">
            <el-form-item class="login-animation1" prop="account">
                <el-input ref="accountRef" text :placeholder="$t('message.account.placeholder1')" v-model="state.ruleForm.account" clearable autocomplete="off" @keyup.enter.native="handleSignIn">
                    <template #prefix>
                        <el-icon>
                            <ele-User />
                        </el-icon>
                    </template>
                </el-input>
            </el-form-item>
            <el-form-item class="login-animation2" prop="password">
                <el-input ref="passwordRef" :type="state.isShowPassword ? 'text' : 'password'" :placeholder="$t('message.account.placeholder2')" v-model="state.ruleForm.password" autocomplete="off" @keyup.enter.native="handleSignIn">
                    <template #prefix>
                        <el-icon>
                            <ele-Unlock />
                        </el-icon>
                    </template>
                    <template #suffix>
                        <i class="iconfont el-input__icon login-content-password" :class="state.isShowPassword ? 'icon-yincangmima' : 'icon-xianshimima'" @click="state.isShowPassword = !state.isShowPassword">
                        </i>
                    </template>
                </el-input>
            </el-form-item>
            <el-form-item class="login-animation2" prop="tenantId" clearable v-if="!props.tenantInfo.id && !state.hideTenantForLogin">
                <el-select v-model="state.ruleForm.tenantId" :placeholder="$t('message.account.placeholder3')" style="width: 100%" filterable>
                    <template #prefix>
                        <i class="iconfont icon-shuxingtu el-input__icon"></i>
                    </template>
                    <el-option :value="item.value" :label="item.label" v-for="(item, index) in tenantInfo.list" :key="index" />
                </el-select>
            </el-form-item>
            <el-form-item class="login-animation3" prop="captcha" v-if="state.captchaEnabled">
                <el-col :span="15">
                    <el-input
                        ref="codeRef"
                        text
                        maxlength="4"
                        :placeholder="$t('message.account.placeholder4')"
                        v-model="state.ruleForm.code"
                        clearable
                        autocomplete="off"
                        @keyup.enter.native="handleSignIn"
                    >
                        <template #prefix>
                            <el-icon>
                                <ele-Position />
                            </el-icon>
                        </template>
                    </el-input>
                </el-col>
                <el-col :span="1"></el-col>
                <el-col :span="8">
                    <div :class="[state.expirySeconds > 0 ? 'login-content-code' : 'login-content-code-expired']" @click="getCaptcha">
                        <img class="login-content-code-img" width="130px" height="38px" :src="state.captchaImage" style="cursor: pointer" />
                    </div>
                </el-col>
            </el-form-item>
            <el-form-item class="login-animation4">
                <el-button type="primary" class="login-content-submit" round v-waves @click="handleSignIn" :loading="state.loading.signIn">
                    <span>{{ $t('message.account.btnText') }}</span>
                </el-button>
            </el-form-item>
            <div class="font12 mt30 login-animation4 login-msg">{{ $t('message.mobile.msgText') }}</div>
            <!-- <el-button type="primary" round v-waves @click="weixinSignIn" :loading="state.loading.signIn"></el-button> -->
        </el-form>
    </el-tooltip>
    <div class="dialog-header">
        <el-dialog v-model="state.rotateVerifyVisible" :show-close="false">
            <DragVerifyImgRotate
                ref="dragRef"
                :imgsrc="state.rotateVerifyImg"
                v-model:isPassing="state.isPassRotate"
                :text="$t('message.account.placeholder6')"
                :successText="$t('message.account.placeholder7')"
                handlerIcon="fa fa-angle-double-right"
                successIcon="fa fa-hand-peace-o"
                @passcallback="passRotateVerify"
            />
        </el-dialog>
    </div>
</template>
 
<script lang="ts" setup name="loginAccount">
import { reactive, computed, ref, onMounted, defineAsyncComponent, onUnmounted, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage, InputInstance } from 'element-plus';
import { useI18n } from 'vue-i18n';
import { initBackEndControlRoutes } from '/@/router/backEnd';
import { Local, Session } from '/@/utils/storage';
import { formatAxis } from '/@/utils/formatTime';
import { NextLoading } from '/@/utils/loading';
import { sm2 } from 'sm-crypto-v2';
import { useThemeConfig } from '/@/stores/themeConfig';
import { storeToRefs } from 'pinia';
 
import { accessTokenKey, clearTokens, feature, getAPI } from '/@/utils/axios-utils';
import { SysAuthApi } from '/@/api-services/api';
 
const props = defineProps({
    tenantInfo: {
        required: true,
        type: Object,
    },
});
 
// 旋转图片滑块组件
// import verifyImg from '/@/assets/logo-mini.svg';
const DragVerifyImgRotate = defineAsyncComponent(() => import('/@/components/dragVerify/dragVerifyImgRotate.vue'));
 
const storesThemeConfig = useThemeConfig();
const { themeConfig } = storeToRefs(storesThemeConfig);
 
const { t } = useI18n();
const route = useRoute();
const router = useRouter();
 
const ruleFormRef = ref();
const accountRef = ref<InputInstance>();
const passwordRef = ref<InputInstance>();
const codeRef = ref<InputInstance>();
 
const dragRef: any = ref(null);
const state = reactive({
    isShowPassword: false,
    ruleForm: {
        // account: window.__env__.VITE_DEFAULT_USER,
        // password: window.__env__.VITE_DEFAULT_USER_PASSWORD,
        account: '',
        password: '',
        tenantId: props.tenantInfo.id,
        code: '',
        codeId: 0,
    },
    rules: {
        account: [{ required: true, message: t('message.account.placeholder1'), trigger: 'blur' }],
        password: [{ required: true, message: t('message.account.placeholder2'), trigger: 'blur' }],
        // code: [{ required: true, message: t('message.account.placeholder4'), trigger: 'blur' }],
    },
    loading: {
        signIn: false,
    },
    captchaImage: '',
    rotateVerifyVisible: false,
    // rotateVerifyImg: verifyImg,
    rotateVerifyImg: themeConfig.value.logoUrl,
    secondVerEnabled: false,
    captchaEnabled: false,
    isPassRotate: false,
    capsLockVisible: false,
    hideTenantForLogin: false,
    expirySeconds: 60, // 验证码过期时间
});
 
// 验证码过期计时器
let timer: any = null;
 
// 页面初始化
onMounted(async () => {
    // 若URL带有Token参数(第三方登录)
    const accessToken = route.query.token;
    if (accessToken) await saveTokenAndInitRoutes(accessToken);
    watch(
        () => themeConfig.value.isLoaded,
        (isLoaded) => {
            if (isLoaded) {
                // 获取登录配置
                state.hideTenantForLogin = themeConfig.value.hideTenantForLogin ?? true;
                state.secondVerEnabled = themeConfig.value.secondVer ?? true;
                state.captchaEnabled = themeConfig.value.captcha ?? true;
 
                // 获取验证码
                getCaptcha();
 
                // 注册验证码过期计时器
                if (state.captchaEnabled) {
                    timer = setInterval(() => {
                        if (state.expirySeconds > 0) state.expirySeconds -= 1;
                    }, 1000);
                }
            }
        },
        { immediate: true }
    );
 
    // 检测大小写按键/CapsLK
    document.addEventListener('keyup', handleKeyPress);
});
 
// 页面卸载
onUnmounted(() => {
    // 销毁验证码过期计时器
    clearInterval(timer);
    timer = null;
 
    document.removeEventListener('keyup', handleKeyPress);
});
 
// 检测大小写按键
const handleKeyPress = (e: KeyboardEvent) => {
    if (e.getModifierState != undefined)
        state.capsLockVisible = e.getModifierState('CapsLock');
};
 
// 获取验证码
const getCaptcha = async () => {
    if (!state.captchaEnabled) return;
 
    state.ruleForm.code = '';
    const res = await getAPI(SysAuthApi).apiSysAuthCaptchaGet().then(res => res.data.result);
    state.captchaImage = 'data:text/html;base64,' + res?.img;
    state.expirySeconds = res?.expirySeconds;
    state.ruleForm.codeId = res?.id;
};
 
// 获取时间
const currentTime = computed(() => {
    return formatAxis(new Date());
});
 
// 登录
const onSignIn = async () => {
    ruleFormRef.value.validate(async (valid: boolean) => {
        if (!valid) return false;
 
        try {
            state.loading.signIn = true;
 
            // SM2加密密码
            // const keys = SM2.generateKeyPair();
            const publicKey = window.__env__.VITE_SM_PUBLIC_KEY;
            const password = sm2.doEncrypt(state.ruleForm.password, publicKey, 1);
 
            state.ruleForm.tenantId ??= props.tenantInfo.id ?? props.tenantInfo.list[0]?.value ?? undefined;
            // console.log(state.ruleForm.tenantId);
            const [err, res] = await feature(getAPI(SysAuthApi).apiSysAuthLoginPost({ ...state.ruleForm, password: password } as any));
            if (err) {
                getCaptcha(); // 重新获取验证码
                return;
            }
            if (res.data.result?.accessToken == undefined) {
                getCaptcha(); // 重新获取验证码
                ElMessage.error(t('message.account.placeholder8'));
                return;
            }
            await saveTokenAndInitRoutes(res.data.result?.accessToken);
        } finally {
            state.loading.signIn = false;
        }
    });
};
 
// 保持Token并初始化路由
const saveTokenAndInitRoutes = async (accessToken: string | any) => {
    // 缓存token
    Local.set(accessTokenKey, accessToken);
    // Local.set(refreshAccessTokenKey, refreshAccessToken);
    Session.set('token', accessToken);
 
    // 添加完动态路由再进行router跳转,否则可能报错 No match found for location with path "/"
    const isNoPower = await initBackEndControlRoutes();
    signInSuccess(isNoPower); // 再执行 signInSuccess
};
 
// 登录成功后的跳转
const signInSuccess = (isNoPower: boolean | undefined) => {
    if (isNoPower) {
        ElMessage.warning(t('message.account.placeholder9'));
        clearTokens(); // 清空Token缓存
    } else {
        // 初始化登录成功时间问候语
        let currentTimeInfo = currentTime.value;
        // 登录成功,跳到转首页 如果是复制粘贴的路径,非首页/登录页,那么登录成功后重定向到对应的路径中
        if (route.query?.redirect) {
            router.push({
                path: <string>route.query?.redirect,
                query: Object.keys(<string>route.query?.params).length > 0 ? JSON.parse(<string>route.query?.params) : '',
            });
        } else {
            router.push('/');
        }
 
        // 登录成功提示
        const signInText = t('message.signInText');
        ElMessage.success(`${currentTimeInfo},${signInText}`);
        // 添加 loading,防止第一次进入界面时出现短暂空白
        NextLoading.start();
    }
};
 
// 打开旋转验证
const openRotateVerify = () => {
    state.rotateVerifyVisible = true;
    state.isPassRotate = false;
    dragRef.value?.reset();
};
 
// 通过旋转验证
const passRotateVerify = () => {
    state.rotateVerifyVisible = false;
    state.isPassRotate = true;
    onSignIn();
};
 
// 登录处理
const handleSignIn = () => {
    if (!state.ruleForm.account) {
        accountRef.value?.focus();
    } else if (!state.ruleForm.password) {
        passwordRef.value?.focus();
    } else if (state.captchaEnabled && !state.ruleForm.code) {
        codeRef.value?.focus();
    } else {
        state.secondVerEnabled ? openRotateVerify() : onSignIn();
    }
};
 
// 导出对象
defineExpose({ saveTokenAndInitRoutes });
</script>
 
<style lang="scss" scoped>
.dialog-header {
    :deep(.el-dialog) {
        width: unset !important;
 
        .el-dialog__header {
            display: none;
        }
 
        .el-dialog__wrapper {
            position: absolute !important;
        }
 
        .v-modal {
            position: absolute !important;
        }
    }
}
 
.login-content-form {
    margin-top: 20px;
 
    @for $i from 0 through 4 {
        .login-animation#{$i} {
            opacity: 0;
            animation-name: error-num;
            animation-duration: 0.5s;
            animation-fill-mode: forwards;
            animation-delay: calc($i/10) + s;
        }
    }
 
    .login-content-password {
        display: inline-block;
        width: 20px;
        cursor: pointer;
 
        &:hover {
            color: #909399;
        }
    }
 
    .login-content-code {
        display: flex;
        align-items: center;
        justify-content: space-around;
        position: relative;
 
        .login-content-code-img {
            width: 100%;
            height: 40px;
            line-height: 40px;
            background-color: #ffffff;
            border: 1px solid rgb(220, 223, 230);
            cursor: pointer;
            transition: all ease 0.2s;
            border-radius: 4px;
            user-select: none;
 
            &:hover {
                border-color: #c0c4cc;
                transition: all ease 0.2s;
            }
        }
    }
 
    .login-content-code-expired {
        @extend .login-content-code;
        &::before {
            content: '验证码已过期';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            border-radius: 4px;
            background-color: rgba(0, 0, 0, 0.5);
            color: #ffffff;
            text-align: center;
        }
    }
 
    .login-content-submit {
        width: 100%;
        letter-spacing: 2px;
        font-weight: 300;
        margin-top: 15px;
    }
 
    .login-msg {
        color: var(--el-text-color-placeholder);
    }
}
</style>