广丰卷烟厂数采质量分析系统
zhuguifei
2026-03-02 974c7aa4010d77bb410b99931b4435d5442deb4b
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
import { computed, reactive, ref } from 'vue';
import { useRoute } from 'vue-router';
import { defineStore } from 'pinia';
import { useLoading } from '@sa/hooks';
import { fetchGetUserInfo, fetchLogin, fetchLogout } from '@/service/api';
import { useRouterPush } from '@/hooks/common/router';
import { localStg } from '@/utils/storage';
import { SetupStoreId } from '@/enum';
import { useRouteStore } from '../route';
import { useTabStore } from '../tab';
import useNoticeStore from '../notice';
import { clearAuthStorage, getToken } from './shared';
 
export const useAuthStore = defineStore(SetupStoreId.Auth, () => {
  const route = useRoute();
  const authStore = useAuthStore();
  const routeStore = useRouteStore();
  const tabStore = useTabStore();
  const noticeStore = useNoticeStore();
  const { toLogin, redirectFromLogin } = useRouterPush(false);
  const { loading: loginLoading, startLoading, endLoading } = useLoading();
 
  const token = ref(getToken());
 
  const userInfo: Api.Auth.UserInfo = reactive({
    user: undefined,
    roles: [],
    permissions: []
  });
 
  /** is super role in static route */
  const isStaticSuper = computed(() => {
    const { VITE_AUTH_ROUTE_MODE, VITE_STATIC_SUPER_ROLE } = import.meta.env;
 
    return VITE_AUTH_ROUTE_MODE === 'static' && userInfo.roles.includes(VITE_STATIC_SUPER_ROLE);
  });
 
  /** Is login */
  const isLogin = computed(() => Boolean(token.value));
 
  /** Reset auth store */
  async function resetStore() {
    recordUserId();
 
    clearAuthStorage();
 
    authStore.$reset();
 
    if (!route.meta.constant) {
      await toLogin();
    }
 
    noticeStore.clearNotice();
    tabStore.cacheTabs();
    routeStore.resetStore();
  }
 
  async function logout() {
    await fetchLogout();
    resetStore();
  }
 
  /** Record the user ID of the previous login session Used to compare with the current user ID on next login */
  function recordUserId() {
    if (!userInfo.user?.userId) {
      return;
    }
 
    // Store current user ID locally for next login comparison
    localStg.set('lastLoginUserId', userInfo.user?.userId);
  }
 
  /**
   * Check if current login user is different from previous login user If different, clear all tabs
   *
   * @returns {boolean} Whether to clear all tabs
   */
  function checkTabClear(): boolean {
    if (!userInfo.user?.userId) {
      return false;
    }
 
    const lastLoginUserId = localStg.get('lastLoginUserId');
 
    // Clear all tabs if current user is different from previous user
    if (!lastLoginUserId || lastLoginUserId !== userInfo.user?.userId) {
      localStg.remove('globalTabs');
      tabStore.clearTabs();
 
      localStg.remove('lastLoginUserId');
      return true;
    }
 
    localStg.remove('lastLoginUserId');
    return false;
  }
 
  /**
   * Login
   *
   * @param [redirect=true] Whether to redirect after login. Default is `true`
   */
  async function login(loginForm: Api.Auth.PwdLoginForm | Api.Auth.SocialLoginForm, redirect = true) {
    startLoading();
 
    const { VITE_APP_CLIENT_ID } = import.meta.env;
 
    const loginData: Api.Auth.PwdLoginForm = {
      ...loginForm,
      tenantId: loginForm.tenantId ?? '000000',
      clientId: VITE_APP_CLIENT_ID!,
      grantType: loginForm.grantType ?? 'password'
    };
 
    const { data: loginToken, error } = await fetchLogin(loginData);
 
    if (!error) {
      const pass = await loginByToken(loginToken);
 
      if (pass) {
        // Check if the tab needs to be cleared
        const isClear = checkTabClear();
        let needRedirect = redirect;
 
        if (isClear) {
          // If the tab needs to be cleared,it means we don't need to redirect.
          needRedirect = false;
        }
        await redirectFromLogin(needRedirect);
 
        // window.$notification?.success({
        //   title: $t('page.login.common.loginSuccess'),
        //   content: $t('page.login.common.welcomeBack', { userName: userInfo.userName }),
        //   duration: 4500
        // });
      }
    } else {
      resetStore();
    }
 
    endLoading();
 
    return error ? Promise.reject(error) : Promise.resolve();
  }
 
  async function loginByToken(loginToken: Api.Auth.LoginToken) {
    // 1. stored in the localStorage, the later requests need it in headers
    localStg.set('token', loginToken.access_token!);
    localStg.set('refreshToken', loginToken.refresh_token!);
 
    // 2. get user info
    const pass = await getUserInfo();
 
    if (pass) {
      token.value = loginToken.access_token!;
 
      return true;
    }
 
    return false;
  }
 
  async function getUserInfo() {
    const { data: info, error } = await fetchGetUserInfo();
 
    if (!error) {
      // update store
      Object.assign(userInfo, info);
 
      return true;
    }
 
    return false;
  }
 
  async function initUserInfo() {
    const hasToken = getToken();
 
    if (hasToken) {
      const pass = await getUserInfo();
 
      if (!pass) {
        resetStore();
      }
    }
  }
 
  return {
    token,
    userInfo,
    isStaticSuper,
    isLogin,
    loginLoading,
    resetStore,
    login,
    logout,
    initUserInfo
  };
});