ny
22 小时以前 282fbc6488f4e8ceb5fda759f963ee88fbf7b999
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
import type { GetUserInfoModel, UserInfo } from '@vben/types';
 
import type { AuthApi } from '#/api';
 
import { h, ref } from 'vue';
import { useRouter } from 'vue-router';
 
import { useMessage } from '@jnpf/hooks';
import { encryptByMd5, formatToDateTime } from '@jnpf/utils';
 
import { LOGIN_PATH } from '@vben/constants';
import { preferences, updatePreferences } from '@vben/preferences';
import { resetAllStores, useAccessStore, useUserStore } from '@vben/stores';
 
import { notification } from 'ant-design-vue';
import { cloneDeep } from 'lodash-es';
import { defineStore } from 'pinia';
 
import { getUserInfoApi, loginApi, logoutApi, unlockApi } from '#/api';
import { $t, initLocale } from '#/locales';
import { defaultPreferencesConfig } from '#/utils/constants';
import { getRealJnpfAppEnCode } from '#/utils/jnpf';
 
import { useBaseStore } from './base';
 
export const useAuthStore = defineStore('auth', () => {
  const accessStore = useAccessStore();
  const userStore = useUserStore();
  const baseStore = useBaseStore();
  const router = useRouter();
 
  const loginLoading = ref(false);
 
  /**
   * 异步处理登录操作
   * Asynchronously handle the login process
   * @param params 登录表单数据
   */
  async function authLogin(params: AuthApi.LoginParams) {
    const loginRequestParams: AuthApi.LoginParams = { ...params };
    // 异步处理用户登录操作并获取 accessToken
    let userInfo: null | UserInfo = null;
    try {
      loginLoading.value = true;
      const res = await loginApi(loginRequestParams);
      const { token: accessToken } = res.data;
 
      // 如果成功获取到 accessToken
      if (accessToken) {
        accessStore.setAccessToken(accessToken);
 
        userInfo = await fetchUserInfo();
        if (!userInfo) return;
        userStore.setUserInfo(userInfo);
 
        if (accessStore.loginExpired) {
          accessStore.setLoginExpired(false);
        }
 
        if (userInfo?.prevLogin === 1) {
          notification?.destroy();
          notification.open({
            message: $t('sys.login.lastLoginInfo'),
            description: () =>
              h('div', { class: 'pt-[10px]' }, [
                h('p', null, `时间: ${formatToDateTime(userInfo?.prevLoginTime)}`),
                h('p', null, `地点: ${userInfo?.prevLoginIPAddressName || ''}`),
                h('p', null, `IP: ${userInfo?.prevLoginIPAddress || ''}`),
              ]),
            placement: 'bottomRight',
            style: { width: '300px' },
          });
        }
      }
    } finally {
      loginLoading.value = false;
    }
 
    return userInfo;
  }
 
  async function logout(redirect: boolean = true) {
    try {
      if (accessStore.accessToken) {
        const res = await logoutApi();
        // 单点登录退出登录
        if (res?.data?.ssoLogoutApiUrl) {
          const iframe: any = document.createElement('IFRAME');
          iframe.setAttribute('style', 'position:absolute;width:0px;height:0px;left:-500px;top:-500px;');
          iframe.src = res?.data.ssoLogoutApiUrl;
          iframe.addEventListener('load', () => {
            iframe.remove();
          });
          document.body.append(iframe);
        }
      }
    } catch {
      // 不做任何处理
    }
 
    resetAllStores();
    accessStore.setLoginExpired(false);
    if (router.currentRoute.value.path === LOGIN_PATH) return;
 
    // 回登陆页带上当前路由地址
    await router.replace({
      path: LOGIN_PATH,
      query: redirect
        ? {
            redirect: encodeURIComponent(router.currentRoute.value.fullPath),
          }
        : {},
    });
  }
 
  async function fetchUserInfo() {
    const res = await getUserInfoApi();
    if (!res) return null;
    const { userInfo, sysConfigInfo, menuList = [], permissionList = [] } = res.data as GetUserInfoModel;
    initLocale(preferences.app.locale);
    handleUpdatePreferences(userInfo);
 
    baseStore.setSysConfig(sysConfigInfo);
    userStore.setUserInfo(userInfo);
    accessStore.setBackMenus(menuList);
    accessStore.setPermissionList(permissionList);
    return userInfo;
  }
 
  // 更新偏好配置
  function handleUpdatePreferences(userInfo) {
    const appEnCode = getRealJnpfAppEnCode();
    let preferenceJson: any = cloneDeep(defaultPreferencesConfig);
    try {
      if (userInfo.preferenceJson) preferenceJson = JSON.parse(userInfo.preferenceJson);
    } catch {
      preferenceJson = cloneDeep(defaultPreferencesConfig);
    }
    if (!appEnCode) preferenceJson.app.layout = 'mixed-nav';
    if (appEnCode && ['teamwork', 'workFlow'].includes(appEnCode)) preferenceJson.app.layout = 'sidebar-nav';
    updatePreferences(preferenceJson);
  }
 
  function confirmLoginOut() {
    const { createConfirm } = useMessage();
    createConfirm({
      iconType: 'warning',
      title: () => h('span', $t('sys.app.logoutTip')),
      content: () => h('span', $t('sys.app.logoutMessage')),
      onOk: async () => {
        await logout(false);
      },
    });
  }
  // 锁屏解锁
  async function unLock(password) {
    const userStore = useUserStore();
    try {
      const account = userStore.getUserInfo?.userAccount;
      const res = await unlockApi({
        account,
        password: encryptByMd5(password),
      });
      return res;
    } catch {
      return false;
    }
  }
  function goForbidden() {
    router.replace('/forbidden');
  }
 
  function $reset() {
    loginLoading.value = false;
  }
 
  return {
    $reset,
    authLogin,
    fetchUserInfo,
    loginLoading,
    logout,
    confirmLoginOut,
    unLock,
    goForbidden,
  };
});