Files
arcticnewone/app/stores/user.ts
T
virtheart 4bef241544 feat: 新增 Nitro Server API 与 PostgreSQL 后端,接入用户系统/联系表单/资讯订阅
- server/api: 注册/登录/登出/会话恢复(JWT + httpOnly Cookie, bcrypt 密码哈希)
- server/api: 联系表单与资讯订阅入库,支持 SMTP 邮件通知(可选)
- 应用启动自动建表(幂等),docker-compose 新增 PostgreSQL 16 服务
- 前端移除全部 mock:user store、登录注册弹窗、联系表单、页脚订阅接入真实接口
- i18n 补充服务端错误码中英文案,移除 demoHint
- deploy: Deployment 环境变量(Secret 引用)、可选集群内 PostgreSQL(postgres.yaml)
- 新增 .env.example 与 README/deploy 文档更新
2026-08-06 06:49:14 +08:00

90 lines
2.5 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
export interface User {
id: number
username: string
email: string
phone?: string
avatarUrl?: string
}
/**
* 从服务端错误响应中提取 i18n 错误码(如 'auth.emailTaken')
*/
function extractErrorCode(err: any): string {
return err?.data?.statusMessage || err?.statusMessage || ''
}
export const useUserStore = defineStore('user', () => {
const user = ref<User | null>(null)
const isAuthenticated = computed(() => user.value !== null)
// 登录(服务端校验账号密码,成功后写入 httpOnly Cookie)
const login = async (account: string, password: string) => {
try {
const data = await $fetch<{ success: true; user: User }>('/api/auth/login', {
method: 'POST',
body: { account, password },
})
user.value = data.user
return { success: true as const }
} catch (err) {
const code = extractErrorCode(err)
return { success: false as const, error: code || 'auth.loginError' }
}
}
// 注册(成功后自动登录)
const register = async (data: { username: string; email: string; phone?: string; password: string }) => {
try {
const res = await $fetch<{ success: true; user: User }>('/api/auth/register', {
method: 'POST',
body: data,
})
user.value = res.user
return { success: true as const }
} catch (err) {
const code = extractErrorCode(err)
return { success: false as const, error: code || 'auth.registerError' }
}
}
// 登出(清除服务端 Cookie)
const logout = async () => {
try {
await $fetch('/api/auth/logout', { method: 'POST' })
} catch {
// 忽略登出接口异常,本地状态照常清理
}
user.value = null
}
// 从 httpOnly Cookie 恢复登录状态(替代旧的 localStorage 假恢复)
const restoreUser = async () => {
try {
const data = await $fetch<{ user: User | null }>('/api/auth/me')
user.value = data.user
} catch {
user.value = null
}
}
// 头像兜底:无自定义头像时用 ui-avatars 生成(保持与旧版一致的视觉)
const avatar = computed(() => {
if (user.value?.avatarUrl) return user.value.avatarUrl
const name = user.value?.username || 'U'
return `https://ui-avatars.com/api/?name=${encodeURIComponent(name)}&background=000&color=fff&size=128`
})
return {
user,
isAuthenticated,
avatar,
login,
logout,
register,
restoreUser,
}
})