337eb4f05a
- 移除内置密码注册/登录/改密/删号/头像,统一走 Casdoor OIDC 授权码 - 服务端 casdoor-nodejs-sdk:code 换 token + 证书公钥验签 + get-account 补齐资料 - 用户表重建为 provider+provider_id(Casdoor sub 为准),邮箱不再唯一 - 管理员由 Casdoor token 的 isAdmin/IsAdmin 字段或 admin 角色判定,删除角色切换接口 - 前端登录弹窗改为申统认证跳转,注册去 Casdoor;后台用户列表只读角色 - 会话沿用 an_session httpOnly Cookie,requireUser/requireAdmin 守卫保留 - 配置注入 deploy.sh/.env.example;新增 casdoor 单测,删除 password 单测
84 lines
2.5 KiB
TypeScript
84 lines
2.5 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
|
|
}
|
|
}
|
|
|
|
// 仅支持修改用户名(头像/邮箱等账号信息统一由 Casdoor 管理)
|
|
const updateProfile = async (patch: { username?: 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,
|
|
}
|
|
}) |