新增功能: - 支持 Google Authenticator 等应用进行 TOTP 二次验证 - 用户可在个人设置中启用/禁用 2FA - 登录时支持 TOTP 验证流程 - 管理后台可全局开关 TOTP 功能 安全增强: - TOTP 密钥使用 AES-256-GCM 加密存储 - 添加 TOTP_ENCRYPTION_KEY 配置项,必须手动配置才能启用功能 - 防止服务重启导致加密密钥变更使用户无法登录 - 验证失败次数限制,防止暴力破解 配置说明: - Docker 部署:在 .env 中设置 TOTP_ENCRYPTION_KEY - 非 Docker 部署:在 config.yaml 中设置 totp.encryption_key - 生成密钥命令:openssl rand -hex 32
296 lines
7.7 KiB
TypeScript
296 lines
7.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, isTotp2FARequired, type LoginResponse } from '@/api'
|
||
import type { User, LoginRequest, RegisterRequest, AuthResponse } 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 (email and password)
|
||
* @returns Promise resolving to the login response (may require 2FA)
|
||
* @throws Error if login fails
|
||
*/
|
||
async function login(credentials: LoginRequest): Promise<LoginResponse> {
|
||
try {
|
||
const response = await authAPI.login(credentials)
|
||
|
||
// If 2FA is required, return the response without setting auth state
|
||
if (isTotp2FARequired(response)) {
|
||
return response
|
||
}
|
||
|
||
// Set auth state from the response
|
||
setAuthFromResponse(response)
|
||
|
||
return response
|
||
} catch (error) {
|
||
// Clear any partial state on error
|
||
clearAuth()
|
||
throw error
|
||
}
|
||
}
|
||
|
||
/**
|
||
* Complete login with 2FA code
|
||
* @param tempToken - Temporary token from initial login
|
||
* @param totpCode - 6-digit TOTP code
|
||
* @returns Promise resolving to the authenticated user
|
||
* @throws Error if 2FA verification fails
|
||
*/
|
||
async function login2FA(tempToken: string, totpCode: string): Promise<User> {
|
||
try {
|
||
const response = await authAPI.login2FA({ temp_token: tempToken, totp_code: totpCode })
|
||
setAuthFromResponse(response)
|
||
return user.value!
|
||
} catch (error) {
|
||
clearAuth()
|
||
throw error
|
||
}
|
||
}
|
||
|
||
/**
|
||
* Set auth state from an AuthResponse
|
||
* Internal helper function
|
||
*/
|
||
function setAuthFromResponse(response: AuthResponse): void {
|
||
// Store token and user
|
||
token.value = response.access_token
|
||
|
||
// Extract run_mode if present
|
||
if (response.user.run_mode) {
|
||
runMode.value = response.user.run_mode
|
||
}
|
||
const { run_mode: _run_mode, ...userData } = response.user
|
||
user.value = userData
|
||
|
||
// Persist to localStorage
|
||
localStorage.setItem(AUTH_TOKEN_KEY, response.access_token)
|
||
localStorage.setItem(AUTH_USER_KEY, JSON.stringify(userData))
|
||
|
||
// Start auto-refresh interval
|
||
startAutoRefresh()
|
||
}
|
||
|
||
/**
|
||
* 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
|
||
|
||
// Extract run_mode if present
|
||
if (response.user.run_mode) {
|
||
runMode.value = response.user.run_mode
|
||
}
|
||
const { run_mode: _run_mode, ...userDataWithoutRunMode } = response.user
|
||
user.value = userDataWithoutRunMode
|
||
|
||
// Persist to localStorage
|
||
localStorage.setItem(AUTH_TOKEN_KEY, response.access_token)
|
||
localStorage.setItem(AUTH_USER_KEY, JSON.stringify(userDataWithoutRunMode))
|
||
|
||
// Start auto-refresh interval
|
||
startAutoRefresh()
|
||
|
||
return userDataWithoutRunMode
|
||
} catch (error) {
|
||
// Clear any partial state on error
|
||
clearAuth()
|
||
throw error
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 直接设置 token(用于 OAuth/SSO 回调),并加载当前用户信息。
|
||
* @param newToken - 后端签发的 JWT access token
|
||
*/
|
||
async function setToken(newToken: string): Promise<User> {
|
||
// Clear any previous state first (avoid mixing sessions)
|
||
clearAuth()
|
||
|
||
token.value = newToken
|
||
localStorage.setItem(AUTH_TOKEN_KEY, newToken)
|
||
|
||
try {
|
||
const userData = await refreshUser()
|
||
startAutoRefresh()
|
||
return userData
|
||
} catch (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: _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,
|
||
login2FA,
|
||
register,
|
||
setToken,
|
||
logout,
|
||
checkAuth,
|
||
refreshUser
|
||
}
|
||
})
|