longz
2026-04-27 25df88d0ab9d7444ed1d162b9efa1259ac2f6f66
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
import { defineStore, getActivePinia } from 'pinia'
import type { MiniUserProfile } from '@/types/auth'
 
export const MINI_AUTH_STORAGE_KEY = 'miniAuth'
 
export interface MiniAuthState {
  token: string
  profile: MiniUserProfile | null
}
 
function createInitialState(): MiniAuthState {
  return {
    token: '',
    profile: null,
  }
}
 
function isValidProfile(value: unknown): value is MiniUserProfile {
  if (!value || typeof value !== 'object') {
    return false
  }
  return typeof (value as MiniUserProfile).mpUserId === 'number'
}
 
export function getPersistedAuthState(): MiniAuthState {
  const state = uni.getStorageSync(MINI_AUTH_STORAGE_KEY) as Partial<MiniAuthState> | undefined
  return {
    token: typeof state?.token === 'string' ? state.token : '',
    profile: isValidProfile(state?.profile) ? state.profile : null,
  }
}
 
export function getPersistedToken(): string {
  return getPersistedAuthState().token
}
 
function writePersistedAuthState(state: MiniAuthState) {
  uni.setStorageSync(MINI_AUTH_STORAGE_KEY, state)
}
 
function patchActiveStore(state: MiniAuthState) {
  const pinia = getActivePinia()
  if (!pinia) {
    return
  }
  const store = useMiniAuthStore(pinia)
  store.$patch(state)
}
 
export function clearMiniAuthSession() {
  const state = createInitialState()
  uni.removeStorageSync(MINI_AUTH_STORAGE_KEY)
  patchActiveStore(state)
}
 
export function updateMiniAuthProfile(profile: MiniUserProfile) {
  const state = {
    ...getPersistedAuthState(),
    profile,
  }
  writePersistedAuthState(state)
  patchActiveStore(state)
}
 
export const useMiniAuthStore = defineStore('miniAuth', {
  state: (): MiniAuthState => createInitialState(),
  getters: {
    isLoggedIn: state => Boolean(state.token),
  },
  actions: {
    setSession(payload: MiniAuthState) {
      this.token = payload.token
      this.profile = payload.profile
      writePersistedAuthState({
        token: payload.token,
        profile: payload.profile,
      })
    },
    setProfile(profile: MiniUserProfile) {
      this.profile = profile
      writePersistedAuthState({
        token: this.token,
        profile,
      })
    },
    clearSession() {
      this.token = ''
      this.profile = null
      uni.removeStorageSync(MINI_AUTH_STORAGE_KEY)
    },
    restoreSession() {
      const state = getPersistedAuthState()
      this.token = state.token
      this.profile = state.profile
      return state
    },
  },
})