import { defineStore } from 'pinia' import { ref, computed } from 'vue' export interface User { id: number providerId: string username: string email: string avatar: string | null role: 'user' | 'admin' createdAt: string } export interface ApiResult { success: boolean /** 后端错误码(供 useApiError 翻译),成功时为 null */ code?: string | null } const AVATAR_URL = (name: string) => `https://ui-avatars.com/api/?name=${encodeURIComponent(name)}&background=000&color=fff&size=128` /** * 用户会话状态(Casdoor 统一认证 + 服务端会话,仅恢复/登出两个动作)。 * 登录不在此 store 发起表单请求:点击登录统一跳转 /api/auth/casdoor-login。 */ export const useUserStore = defineStore('user', () => { const user = ref(null) const isAuthenticated = computed(() => user.value !== null) // 跳转 Casdoor 统一登录(next 为回跳路径,仅站内相对路径) const loginRedirect = (next = '/'): void => { const target = next.startsWith('/') && !next.startsWith('//') ? next : '/' const url = `/api/auth/casdoor-login?next=${encodeURIComponent(target)}` if (typeof window !== 'undefined') window.location.assign(url) } // 登出:销毁本地会话并清 Cookie;如需 Casdoor 单点登出再跳转其 logout 地址 const logout = async (): Promise => { try { await $fetch('/api/auth/logout', { method: 'POST' }) } catch (err) { console.error('logout error:', err) } user.value = null } // 从服务端会话恢复用户(应用启动时调用) const restoreUser = async (): Promise => { try { const data = await $fetch<{ user: User }>('/api/auth/me') user.value = data.user } catch (err) { user.value = null } } // 仅支持修改用户名(头像/邮箱等账号信息统一由 Casdoor 管理) const updateProfile = async (patch: { username?: string }): Promise => { try { const data = await $fetch<{ user: User }>('/api/auth/me', { method: 'PATCH', body: patch }) user.value = data.user return { success: true } } catch (err) { return { success: false, code: (err as any)?.data?.code || 'SERVER_ERROR' } } } // 头像:Casdoor 头像优先,否则按用户名生成 const avatar = computed(() => { if (!user.value) return '' return user.value.avatar || AVATAR_URL(user.value.username) }) return { user, isAuthenticated, avatar, loginRedirect, logout, restoreUser, updateProfile, } })