import { defineStore } from 'pinia' import { ref, computed } from 'vue' export interface Admin { id: number username: string createdAt: string } export interface ApiResult { success: boolean /** 后端错误码(供 useApiError 翻译),成功时为 null */ code?: string | null } /** * 后台管理员会话(独立于 Casdoor 前台用户体系,凭 admin_users 表 + 独立 Cookie)。 * - restoreAdmin:从服务端会话恢复当前管理员(启动时由插件调用) * - checkInit:系统是否已创建首个管理员(未创建时客户端强制引导到 /admin/init) * - login / logout:管理员登录页与侧边栏登出 */ export const useAdminStore = defineStore('admin', () => { const admin = ref(null) const isAuthenticated = computed(() => admin.value !== null) // 系统是否尚未初始化首个管理员(null = 未知,加载中) const needsInit = ref(null) const restoreAdmin = async (): Promise => { try { const data = await $fetch<{ admin: Admin }>('/api/auth/admin/me') admin.value = data.admin } catch { admin.value = null } } const checkInit = async (): Promise => { try { const data = await $fetch<{ needsInit: boolean }>('/api/auth/admin-init-status') needsInit.value = data.needsInit } catch { needsInit.value = false } } const login = async (username: string, password: string): Promise => { try { const data = await $fetch<{ admin: Admin }>('/api/auth/admin/login', { method: 'POST', body: { username, password }, }) admin.value = data.admin return { success: true } } catch (err) { return { success: false, code: (err as any)?.data?.code || 'SERVER_ERROR' } } } const logout = async (): Promise => { try { await $fetch('/api/auth/admin/logout', { method: 'POST' }) } catch (err) { console.error('admin logout error:', err) } admin.value = null } return { admin, isAuthenticated, needsInit, restoreAdmin, checkInit, login, logout } })