仰望星辰工作室

better-staridc-MNBT

Z zfhsh first commit 2 个月前
1import { reactive } from 'vue'
2import { getMe } from '@/home/api/account'
3
4/**
5 * 共享登录态 store
6 * user_info 插件认证(account_token cookie)
7 */
8export const authState = reactive({
9 loading: false,
10 loggedIn: false,
11 user: null,
12 initialized: false,
13})
14
15/** 探测当前登录态(不弹窗)
16 * @param {boolean} force 强制重新探测;false 时若已有探测在途则复用,避免并发早退
17 */
18export async function initAuth(force = false) {
19 if (authState.loading && !force) return authState
20 authState.loading = true
21 try {
22 const res = await getMe()
23 if (res.ok && res.data?.logged_in) {
24 authState.loggedIn = true
25 authState.user = res.data.user || null
26 } else {
27 authState.loggedIn = false
28 authState.user = null
29 }
30 } catch {
31 authState.loggedIn = false
32 authState.user = null
33 } finally {
34 authState.loading = false
35 authState.initialized = true
36 }
37 return authState
38}
39
40/** 清除本地登录态(退出/失效时调用) */
41export function resetAuth() {
42 authState.loggedIn = false
43 authState.user = null
44 authState.initialized = true
45}
46
47export default authState