Files
sub2api/frontend/src/stores/auth.ts

263 lines
6.7 KiB
TypeScript
Raw Normal View History

2025-12-18 13:50:39 +08:00
/**
* 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'
2025-12-18 13:50:39 +08:00
const AUTH_TOKEN_KEY = 'auth_token'
const AUTH_USER_KEY = 'auth_user'
const AUTO_REFRESH_INTERVAL = 60 * 1000 // 60 seconds
2025-12-18 13:50:39 +08:00
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
2025-12-18 13:50:39 +08:00
// ==================== Computed ====================
const isAuthenticated = computed(() => {
return !!token.value && !!user.value
})
2025-12-18 13:50:39 +08:00
const isAdmin = computed(() => {
return user.value?.role === 'admin'
})
2025-12-18 13:50:39 +08:00
const isSimpleMode = computed(() => runMode.value === 'simple')
2025-12-18 13:50:39 +08:00
// ==================== 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)
2025-12-18 13:50:39 +08:00
if (savedToken && savedUser) {
try {
token.value = savedToken
user.value = JSON.parse(savedUser)
2025-12-18 13:50:39 +08:00
// Immediately refresh user data from backend (async, don't block)
refreshUser().catch((error) => {
console.error('Failed to refresh user on init:', error)
})
2025-12-18 13:50:39 +08:00
// Start auto-refresh interval
startAutoRefresh()
2025-12-18 13:50:39 +08:00
} catch (error) {
console.error('Failed to parse saved user data:', error)
clearAuth()
2025-12-18 13:50:39 +08:00
}
}
}
/**
* Start auto-refresh interval for user data
* Refreshes user data every 60 seconds
*/
function startAutoRefresh(): void {
// Clear existing interval if any
stopAutoRefresh()
2025-12-18 13:50:39 +08:00
refreshIntervalId = setInterval(() => {
if (token.value) {
refreshUser().catch((error) => {
console.error('Auto-refresh user failed:', error)
})
2025-12-18 13:50:39 +08:00
}
}, AUTO_REFRESH_INTERVAL)
2025-12-18 13:50:39 +08:00
}
/**
* Stop auto-refresh interval
*/
function stopAutoRefresh(): void {
if (refreshIntervalId) {
clearInterval(refreshIntervalId)
refreshIntervalId = null
2025-12-18 13:50:39 +08:00
}
}
/**
* 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)
2025-12-18 13:50:39 +08:00
// 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
2025-12-18 13:50:39 +08:00
// Persist to localStorage
localStorage.setItem(AUTH_TOKEN_KEY, response.access_token)
localStorage.setItem(AUTH_USER_KEY, JSON.stringify(userData))
2025-12-18 13:50:39 +08:00
// Start auto-refresh interval
startAutoRefresh()
2025-12-18 13:50:39 +08:00
return userData
2025-12-18 13:50:39 +08:00
} catch (error) {
// Clear any partial state on error
clearAuth()
throw error
2025-12-18 13:50:39 +08:00
}
}
/**
* 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)
2025-12-18 13:50:39 +08:00
// 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
2025-12-18 13:50:39 +08:00
// Persist to localStorage
localStorage.setItem(AUTH_TOKEN_KEY, response.access_token)
localStorage.setItem(AUTH_USER_KEY, JSON.stringify(userDataWithoutRunMode))
2025-12-18 13:50:39 +08:00
// Start auto-refresh interval
startAutoRefresh()
2025-12-18 13:50:39 +08:00
return userDataWithoutRunMode
2025-12-18 13:50:39 +08:00
} catch (error) {
// Clear any partial state on error
clearAuth()
throw error
2025-12-18 13:50:39 +08:00
}
}
/**
* 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
}
}
2025-12-18 13:50:39 +08:00
/**
* User logout
* Clears all authentication state and persisted data
*/
function logout(): void {
// Call API logout (client-side cleanup)
authAPI.logout()
2025-12-18 13:50:39 +08:00
// Clear state
clearAuth()
2025-12-18 13:50:39 +08:00
}
/**
* 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')
2025-12-18 13:50:39 +08:00
}
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
2025-12-18 13:50:39 +08:00
// Update localStorage
localStorage.setItem(AUTH_USER_KEY, JSON.stringify(userData))
2025-12-18 13:50:39 +08:00
return userData
2025-12-18 13:50:39 +08:00
} catch (error) {
// If refresh fails with 401, clear auth state
if ((error as { status?: number }).status === 401) {
clearAuth()
2025-12-18 13:50:39 +08:00
}
throw error
2025-12-18 13:50:39 +08:00
}
}
/**
* Clear all authentication state
* Internal helper function
*/
function clearAuth(): void {
// Stop auto-refresh
stopAutoRefresh()
2025-12-18 13:50:39 +08:00
token.value = null
user.value = null
localStorage.removeItem(AUTH_TOKEN_KEY)
localStorage.removeItem(AUTH_USER_KEY)
2025-12-18 13:50:39 +08:00
}
// ==================== Return Store API ====================
return {
// State
user,
token,
runMode: readonly(runMode),
2025-12-18 13:50:39 +08:00
// Computed
isAuthenticated,
isAdmin,
isSimpleMode,
2025-12-18 13:50:39 +08:00
// Actions
login,
register,
setToken,
2025-12-18 13:50:39 +08:00
logout,
checkAuth,
refreshUser
}
})