f9e5ce61e3
- 站内改昵称/邮箱/头像后,用自己的 access_token 写回 Casimir(update-user,字段每批≤2,401 自动 refresh_token 续期) - 头像不再本地存储:上传直调 Casimir upload-resource (tag=avatar),成功后自动写回 user.Avatar,仅落库返回 URL - me.patch 头像仅存档本地,避免 update-user 重复同步 - 头像上传仅走 Casimir,未配置 Storage provider 时报错提示 - exchangeCodeForIdentity 补 owner/displayName/token,昵称优先 displayName - 新增类型检查依赖 typescript/vue-tsc 与 typecheck 脚本
84 lines
2.6 KiB
TypeScript
84 lines
2.6 KiB
TypeScript
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<User | null>(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<void> => {
|
|
try {
|
|
await $fetch('/api/auth/logout', { method: 'POST' })
|
|
} catch (err) {
|
|
console.error('logout error:', err)
|
|
}
|
|
user.value = null
|
|
}
|
|
|
|
// 从服务端会话恢复用户(应用启动时调用)
|
|
const restoreUser = async (): Promise<void> => {
|
|
try {
|
|
const data = await $fetch<{ user: User }>('/api/auth/me')
|
|
user.value = data.user
|
|
} catch (err) {
|
|
user.value = null
|
|
}
|
|
}
|
|
|
|
// 修改个人资料:昵称(->Casimir displayName)/邮箱/头像,由后端与 Casimir 同步
|
|
const updateProfile = async (patch: { username?: string; email?: string; avatar?: string }): Promise<ApiResult> => {
|
|
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,
|
|
}
|
|
}) |