Files
sub2api/frontend/src/stores/auth.ts
IanShaw027 ecfad788d9 feat(全栈): 实现简易模式核心功能
**功能概述**:
实现简易模式(Simple Mode),为个人用户和小团队提供简化的使用体验,隐藏复杂的分组、订阅、配额等概念。

**后端改动**:
1. 配置系统
   - 新增 run_mode 配置项(standard/simple)
   - 支持环境变量 RUN_MODE
   - 默认值为 standard

2. 数据库初始化
   - 自动创建3个默认分组:anthropic-default、openai-default、gemini-default
   - 默认分组配置:无并发限制、active状态、非独占
   - 幂等性保证:重复启动不会重复创建

3. 账号管理
   - 创建账号时自动绑定对应平台的默认分组
   - 如果未指定分组,自动查找并绑定默认分组

**前端改动**:
1. 状态管理
   - authStore 新增 isSimpleMode 计算属性
   - 从后端API获取并同步运行模式

2. UI隐藏
   - 侧边栏:隐藏分组管理、订阅管理、兑换码菜单
   - 账号管理页面:隐藏分组列
   - 创建/编辑账号对话框:隐藏分组选择器

3. 路由守卫
   - 限制访问分组、订阅、兑换码相关页面
   - 访问受限页面时自动重定向到仪表板

**配置示例**:
```yaml
run_mode: simple

run_mode: standard
```

**影响范围**:
- 后端:配置、数据库迁移、账号服务
- 前端:认证状态、路由、UI组件
- 部署:配置文件示例

**兼容性**:
- 简易模式和标准模式可无缝切换
- 不需要数据迁移
- 现有数据不受影响
2025-12-29 03:24:15 +08:00

229 lines
5.7 KiB
TypeScript

/**
* Authentication Store
* Manages user authentication state, login/logout, and token persistence
*/
import { defineStore } from 'pinia'
import { ref, computed, readonly } from 'vue'
import { authAPI } from '@/api'
import type { User, LoginRequest, RegisterRequest } from '@/types'
const AUTH_TOKEN_KEY = 'auth_token'
const AUTH_USER_KEY = 'auth_user'
const AUTO_REFRESH_INTERVAL = 60 * 1000 // 60 seconds
export const useAuthStore = defineStore('auth', () => {
// ==================== State ====================
const user = ref<User | null>(null)
const token = ref<string | null>(null)
const runMode = ref<'standard' | 'simple'>('standard')
let refreshIntervalId: ReturnType<typeof setInterval> | null = null
// ==================== Computed ====================
const isAuthenticated = computed(() => {
return !!token.value && !!user.value
})
const isAdmin = computed(() => {
return user.value?.role === 'admin'
})
const isSimpleMode = computed(() => runMode.value === 'simple')
// ==================== Actions ====================
/**
* Initialize auth state from localStorage
* Call this on app startup to restore session
* Also starts auto-refresh and immediately fetches latest user data
*/
function checkAuth(): void {
const savedToken = localStorage.getItem(AUTH_TOKEN_KEY)
const savedUser = localStorage.getItem(AUTH_USER_KEY)
if (savedToken && savedUser) {
try {
token.value = savedToken
user.value = JSON.parse(savedUser)
// Immediately refresh user data from backend (async, don't block)
refreshUser().catch((error) => {
console.error('Failed to refresh user on init:', error)
})
// Start auto-refresh interval
startAutoRefresh()
} catch (error) {
console.error('Failed to parse saved user data:', error)
clearAuth()
}
}
}
/**
* Start auto-refresh interval for user data
* Refreshes user data every 60 seconds
*/
function startAutoRefresh(): void {
// Clear existing interval if any
stopAutoRefresh()
refreshIntervalId = setInterval(() => {
if (token.value) {
refreshUser().catch((error) => {
console.error('Auto-refresh user failed:', error)
})
}
}, AUTO_REFRESH_INTERVAL)
}
/**
* Stop auto-refresh interval
*/
function stopAutoRefresh(): void {
if (refreshIntervalId) {
clearInterval(refreshIntervalId)
refreshIntervalId = null
}
}
/**
* User login
* @param credentials - Login credentials (username and password)
* @returns Promise resolving to the authenticated user
* @throws Error if login fails
*/
async function login(credentials: LoginRequest): Promise<User> {
try {
const response = await authAPI.login(credentials)
// Store token and user
token.value = response.access_token
user.value = response.user
// Persist to localStorage
localStorage.setItem(AUTH_TOKEN_KEY, response.access_token)
localStorage.setItem(AUTH_USER_KEY, JSON.stringify(response.user))
// Start auto-refresh interval
startAutoRefresh()
return response.user
} catch (error) {
// Clear any partial state on error
clearAuth()
throw error
}
}
/**
* User registration
* @param userData - Registration data (username, email, password)
* @returns Promise resolving to the newly registered and authenticated user
* @throws Error if registration fails
*/
async function register(userData: RegisterRequest): Promise<User> {
try {
const response = await authAPI.register(userData)
// Store token and user
token.value = response.access_token
user.value = response.user
// Persist to localStorage
localStorage.setItem(AUTH_TOKEN_KEY, response.access_token)
localStorage.setItem(AUTH_USER_KEY, JSON.stringify(response.user))
// Start auto-refresh interval
startAutoRefresh()
return response.user
} catch (error) {
// Clear any partial state on error
clearAuth()
throw error
}
}
/**
* User logout
* Clears all authentication state and persisted data
*/
function logout(): void {
// Call API logout (client-side cleanup)
authAPI.logout()
// Clear state
clearAuth()
}
/**
* Refresh current user data
* Fetches latest user info from the server
* @returns Promise resolving to the updated user
* @throws Error if not authenticated or request fails
*/
async function refreshUser(): Promise<User> {
if (!token.value) {
throw new Error('Not authenticated')
}
try {
const response = await authAPI.getCurrentUser()
if (response.data.run_mode) {
runMode.value = response.data.run_mode
}
const { run_mode, ...userData } = response.data
user.value = userData
// Update localStorage
localStorage.setItem(AUTH_USER_KEY, JSON.stringify(userData))
return userData
} catch (error) {
// If refresh fails with 401, clear auth state
if ((error as { status?: number }).status === 401) {
clearAuth()
}
throw error
}
}
/**
* Clear all authentication state
* Internal helper function
*/
function clearAuth(): void {
// Stop auto-refresh
stopAutoRefresh()
token.value = null
user.value = null
localStorage.removeItem(AUTH_TOKEN_KEY)
localStorage.removeItem(AUTH_USER_KEY)
}
// ==================== Return Store API ====================
return {
// State
user,
token,
runMode: readonly(runMode),
// Computed
isAuthenticated,
isAdmin,
isSimpleMode,
// Actions
login,
register,
logout,
checkAuth,
refreshUser
}
})