feat(auth): 实现 Refresh Token 机制
- 新增 Access Token + Refresh Token 双令牌认证 - 支持 Token 自动刷新和轮转 - 添加登出和撤销所有会话接口 - 前端实现无感刷新和主动刷新定时器
This commit is contained in:
@@ -35,6 +35,22 @@ export function setAuthToken(token: string): void {
|
||||
localStorage.setItem('auth_token', token)
|
||||
}
|
||||
|
||||
/**
|
||||
* Store refresh token in localStorage
|
||||
*/
|
||||
export function setRefreshToken(token: string): void {
|
||||
localStorage.setItem('refresh_token', token)
|
||||
}
|
||||
|
||||
/**
|
||||
* Store token expiration timestamp in localStorage
|
||||
* Converts expires_in (seconds) to absolute timestamp (milliseconds)
|
||||
*/
|
||||
export function setTokenExpiresAt(expiresIn: number): void {
|
||||
const expiresAt = Date.now() + expiresIn * 1000
|
||||
localStorage.setItem('token_expires_at', String(expiresAt))
|
||||
}
|
||||
|
||||
/**
|
||||
* Get authentication token from localStorage
|
||||
*/
|
||||
@@ -42,12 +58,29 @@ export function getAuthToken(): string | null {
|
||||
return localStorage.getItem('auth_token')
|
||||
}
|
||||
|
||||
/**
|
||||
* Get refresh token from localStorage
|
||||
*/
|
||||
export function getRefreshToken(): string | null {
|
||||
return localStorage.getItem('refresh_token')
|
||||
}
|
||||
|
||||
/**
|
||||
* Get token expiration timestamp from localStorage
|
||||
*/
|
||||
export function getTokenExpiresAt(): number | null {
|
||||
const value = localStorage.getItem('token_expires_at')
|
||||
return value ? parseInt(value, 10) : null
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear authentication token from localStorage
|
||||
*/
|
||||
export function clearAuthToken(): void {
|
||||
localStorage.removeItem('auth_token')
|
||||
localStorage.removeItem('refresh_token')
|
||||
localStorage.removeItem('auth_user')
|
||||
localStorage.removeItem('token_expires_at')
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -61,6 +94,12 @@ export async function login(credentials: LoginRequest): Promise<LoginResponse> {
|
||||
// Only store token if 2FA is not required
|
||||
if (!isTotp2FARequired(data)) {
|
||||
setAuthToken(data.access_token)
|
||||
if (data.refresh_token) {
|
||||
setRefreshToken(data.refresh_token)
|
||||
}
|
||||
if (data.expires_in) {
|
||||
setTokenExpiresAt(data.expires_in)
|
||||
}
|
||||
localStorage.setItem('auth_user', JSON.stringify(data.user))
|
||||
}
|
||||
|
||||
@@ -77,6 +116,12 @@ export async function login2FA(request: TotpLogin2FARequest): Promise<AuthRespon
|
||||
|
||||
// Store token and user data
|
||||
setAuthToken(data.access_token)
|
||||
if (data.refresh_token) {
|
||||
setRefreshToken(data.refresh_token)
|
||||
}
|
||||
if (data.expires_in) {
|
||||
setTokenExpiresAt(data.expires_in)
|
||||
}
|
||||
localStorage.setItem('auth_user', JSON.stringify(data.user))
|
||||
|
||||
return data
|
||||
@@ -92,6 +137,12 @@ export async function register(userData: RegisterRequest): Promise<AuthResponse>
|
||||
|
||||
// Store token and user data
|
||||
setAuthToken(data.access_token)
|
||||
if (data.refresh_token) {
|
||||
setRefreshToken(data.refresh_token)
|
||||
}
|
||||
if (data.expires_in) {
|
||||
setTokenExpiresAt(data.expires_in)
|
||||
}
|
||||
localStorage.setItem('auth_user', JSON.stringify(data.user))
|
||||
|
||||
return data
|
||||
@@ -108,11 +159,62 @@ export async function getCurrentUser() {
|
||||
/**
|
||||
* User logout
|
||||
* Clears authentication token and user data from localStorage
|
||||
* Optionally revokes the refresh token on the server
|
||||
*/
|
||||
export function logout(): void {
|
||||
export async function logout(): Promise<void> {
|
||||
const refreshToken = getRefreshToken()
|
||||
|
||||
// Try to revoke the refresh token on the server
|
||||
if (refreshToken) {
|
||||
try {
|
||||
await apiClient.post('/auth/logout', { refresh_token: refreshToken })
|
||||
} catch {
|
||||
// Ignore errors - we still want to clear local state
|
||||
}
|
||||
}
|
||||
|
||||
clearAuthToken()
|
||||
// Optionally redirect to login page
|
||||
// window.location.href = '/login';
|
||||
}
|
||||
|
||||
/**
|
||||
* Refresh token response
|
||||
*/
|
||||
export interface RefreshTokenResponse {
|
||||
access_token: string
|
||||
refresh_token: string
|
||||
expires_in: number
|
||||
token_type: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Refresh the access token using the refresh token
|
||||
* @returns New token pair
|
||||
*/
|
||||
export async function refreshToken(): Promise<RefreshTokenResponse> {
|
||||
const currentRefreshToken = getRefreshToken()
|
||||
if (!currentRefreshToken) {
|
||||
throw new Error('No refresh token available')
|
||||
}
|
||||
|
||||
const { data } = await apiClient.post<RefreshTokenResponse>('/auth/refresh', {
|
||||
refresh_token: currentRefreshToken
|
||||
})
|
||||
|
||||
// Update tokens in localStorage
|
||||
setAuthToken(data.access_token)
|
||||
setRefreshToken(data.refresh_token)
|
||||
setTokenExpiresAt(data.expires_in)
|
||||
|
||||
return data
|
||||
}
|
||||
|
||||
/**
|
||||
* Revoke all sessions for the current user
|
||||
* @returns Response with message
|
||||
*/
|
||||
export async function revokeAllSessions(): Promise<{ message: string }> {
|
||||
const { data } = await apiClient.post<{ message: string }>('/auth/revoke-all-sessions')
|
||||
return data
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -242,14 +344,20 @@ export const authAPI = {
|
||||
logout,
|
||||
isAuthenticated,
|
||||
setAuthToken,
|
||||
setRefreshToken,
|
||||
setTokenExpiresAt,
|
||||
getAuthToken,
|
||||
getRefreshToken,
|
||||
getTokenExpiresAt,
|
||||
clearAuthToken,
|
||||
getPublicSettings,
|
||||
sendVerifyCode,
|
||||
validatePromoCode,
|
||||
validateInvitationCode,
|
||||
forgotPassword,
|
||||
resetPassword
|
||||
resetPassword,
|
||||
refreshToken,
|
||||
revokeAllSessions
|
||||
}
|
||||
|
||||
export default authAPI
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
/**
|
||||
* Axios HTTP Client Configuration
|
||||
* Base client with interceptors for authentication and error handling
|
||||
* Base client with interceptors for authentication, token refresh, and error handling
|
||||
*/
|
||||
|
||||
import axios, { AxiosInstance, AxiosError, InternalAxiosRequestConfig } from 'axios'
|
||||
import axios, { AxiosInstance, AxiosError, InternalAxiosRequestConfig, AxiosResponse } from 'axios'
|
||||
import type { ApiResponse } from '@/types'
|
||||
import { getLocale } from '@/i18n'
|
||||
|
||||
@@ -19,6 +19,28 @@ export const apiClient: AxiosInstance = axios.create({
|
||||
}
|
||||
})
|
||||
|
||||
// ==================== Token Refresh State ====================
|
||||
|
||||
// Track if a token refresh is in progress to prevent multiple simultaneous refresh requests
|
||||
let isRefreshing = false
|
||||
// Queue of requests waiting for token refresh
|
||||
let refreshSubscribers: Array<(token: string) => void> = []
|
||||
|
||||
/**
|
||||
* Subscribe to token refresh completion
|
||||
*/
|
||||
function subscribeTokenRefresh(callback: (token: string) => void): void {
|
||||
refreshSubscribers.push(callback)
|
||||
}
|
||||
|
||||
/**
|
||||
* Notify all subscribers that token has been refreshed
|
||||
*/
|
||||
function onTokenRefreshed(token: string): void {
|
||||
refreshSubscribers.forEach((callback) => callback(token))
|
||||
refreshSubscribers = []
|
||||
}
|
||||
|
||||
// ==================== Request Interceptor ====================
|
||||
|
||||
// Get user's timezone
|
||||
@@ -61,7 +83,7 @@ apiClient.interceptors.request.use(
|
||||
// ==================== Response Interceptor ====================
|
||||
|
||||
apiClient.interceptors.response.use(
|
||||
(response) => {
|
||||
(response: AxiosResponse) => {
|
||||
// Unwrap standard API response format { code, message, data }
|
||||
const apiResponse = response.data as ApiResponse<unknown>
|
||||
if (apiResponse && typeof apiResponse === 'object' && 'code' in apiResponse) {
|
||||
@@ -79,13 +101,15 @@ apiClient.interceptors.response.use(
|
||||
}
|
||||
return response
|
||||
},
|
||||
(error: AxiosError<ApiResponse<unknown>>) => {
|
||||
async (error: AxiosError<ApiResponse<unknown>>) => {
|
||||
// Request cancellation: keep the original axios cancellation error so callers can ignore it.
|
||||
// Otherwise we'd misclassify it as a generic "network error".
|
||||
if (error.code === 'ERR_CANCELED' || axios.isCancel(error)) {
|
||||
return Promise.reject(error)
|
||||
}
|
||||
|
||||
const originalRequest = error.config as InternalAxiosRequestConfig & { _retry?: boolean }
|
||||
|
||||
// Handle common errors
|
||||
if (error.response) {
|
||||
const { status, data } = error.response
|
||||
@@ -120,23 +144,116 @@ apiClient.interceptors.response.use(
|
||||
})
|
||||
}
|
||||
|
||||
// 401: Unauthorized - clear token and redirect to login
|
||||
if (status === 401) {
|
||||
const hasToken = !!localStorage.getItem('auth_token')
|
||||
const url = error.config?.url || ''
|
||||
// 401: Try to refresh the token if we have a refresh token
|
||||
// This handles TOKEN_EXPIRED, INVALID_TOKEN, TOKEN_REVOKED, etc.
|
||||
if (status === 401 && !originalRequest._retry) {
|
||||
const refreshToken = localStorage.getItem('refresh_token')
|
||||
const isAuthEndpoint =
|
||||
url.includes('/auth/login') || url.includes('/auth/register') || url.includes('/auth/refresh')
|
||||
|
||||
// If we have a refresh token and this is not an auth endpoint, try to refresh
|
||||
if (refreshToken && !isAuthEndpoint) {
|
||||
if (isRefreshing) {
|
||||
// Wait for the ongoing refresh to complete
|
||||
return new Promise((resolve, reject) => {
|
||||
subscribeTokenRefresh((newToken: string) => {
|
||||
if (newToken) {
|
||||
// Mark as retried to prevent infinite loop if retry also returns 401
|
||||
originalRequest._retry = true
|
||||
if (originalRequest.headers) {
|
||||
originalRequest.headers.Authorization = `Bearer ${newToken}`
|
||||
}
|
||||
resolve(apiClient(originalRequest))
|
||||
} else {
|
||||
// Refresh failed, reject with original error
|
||||
reject({
|
||||
status,
|
||||
code: apiData.code,
|
||||
message: apiData.message || apiData.detail || error.message
|
||||
})
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
originalRequest._retry = true
|
||||
isRefreshing = true
|
||||
|
||||
try {
|
||||
// Call refresh endpoint directly to avoid circular dependency
|
||||
const refreshResponse = await axios.post(
|
||||
`${API_BASE_URL}/auth/refresh`,
|
||||
{ refresh_token: refreshToken },
|
||||
{ headers: { 'Content-Type': 'application/json' } }
|
||||
)
|
||||
|
||||
const refreshData = refreshResponse.data as ApiResponse<{
|
||||
access_token: string
|
||||
refresh_token: string
|
||||
expires_in: number
|
||||
}>
|
||||
|
||||
if (refreshData.code === 0 && refreshData.data) {
|
||||
const { access_token, refresh_token: newRefreshToken, expires_in } = refreshData.data
|
||||
|
||||
// Update tokens in localStorage (convert expires_in to timestamp)
|
||||
localStorage.setItem('auth_token', access_token)
|
||||
localStorage.setItem('refresh_token', newRefreshToken)
|
||||
localStorage.setItem('token_expires_at', String(Date.now() + expires_in * 1000))
|
||||
|
||||
// Notify subscribers with new token
|
||||
onTokenRefreshed(access_token)
|
||||
|
||||
// Retry the original request with new token
|
||||
if (originalRequest.headers) {
|
||||
originalRequest.headers.Authorization = `Bearer ${access_token}`
|
||||
}
|
||||
|
||||
isRefreshing = false
|
||||
return apiClient(originalRequest)
|
||||
}
|
||||
|
||||
// Refresh response was not successful, fall through to clear auth
|
||||
throw new Error('Token refresh failed')
|
||||
} catch (refreshError) {
|
||||
// Refresh failed - notify subscribers with empty token
|
||||
onTokenRefreshed('')
|
||||
isRefreshing = false
|
||||
|
||||
// Clear tokens and redirect to login
|
||||
localStorage.removeItem('auth_token')
|
||||
localStorage.removeItem('refresh_token')
|
||||
localStorage.removeItem('auth_user')
|
||||
localStorage.removeItem('token_expires_at')
|
||||
sessionStorage.setItem('auth_expired', '1')
|
||||
|
||||
if (!window.location.pathname.includes('/login')) {
|
||||
window.location.href = '/login'
|
||||
}
|
||||
|
||||
return Promise.reject({
|
||||
status: 401,
|
||||
code: 'TOKEN_REFRESH_FAILED',
|
||||
message: 'Session expired. Please log in again.'
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// No refresh token or is auth endpoint - clear auth and redirect
|
||||
const hasToken = !!localStorage.getItem('auth_token')
|
||||
const headers = error.config?.headers as Record<string, unknown> | undefined
|
||||
const authHeader = headers?.Authorization ?? headers?.authorization
|
||||
const sentAuth =
|
||||
typeof authHeader === 'string'
|
||||
? authHeader.trim() !== ''
|
||||
: Array.isArray(authHeader)
|
||||
? authHeader.length > 0
|
||||
: !!authHeader
|
||||
? authHeader.length > 0
|
||||
: !!authHeader
|
||||
|
||||
localStorage.removeItem('auth_token')
|
||||
localStorage.removeItem('refresh_token')
|
||||
localStorage.removeItem('auth_user')
|
||||
localStorage.removeItem('token_expires_at')
|
||||
if ((hasToken || sentAuth) && !isAuthEndpoint) {
|
||||
sessionStorage.setItem('auth_expired', '1')
|
||||
}
|
||||
|
||||
@@ -283,7 +283,12 @@ function closeDropdown() {
|
||||
|
||||
async function handleLogout() {
|
||||
closeDropdown()
|
||||
authStore.logout()
|
||||
try {
|
||||
await authStore.logout()
|
||||
} catch (error) {
|
||||
// Ignore logout errors - still redirect to login
|
||||
console.error('Logout error:', error)
|
||||
}
|
||||
await router.push('/login')
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
/**
|
||||
* Authentication Store
|
||||
* Manages user authentication state, login/logout, and token persistence
|
||||
* Manages user authentication state, login/logout, token refresh, and token persistence
|
||||
*/
|
||||
|
||||
import { defineStore } from 'pinia'
|
||||
@@ -10,15 +10,21 @@ 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
|
||||
const REFRESH_TOKEN_KEY = 'refresh_token'
|
||||
const TOKEN_EXPIRES_AT_KEY = 'token_expires_at' // 存储过期时间戳而非有效期
|
||||
const AUTO_REFRESH_INTERVAL = 60 * 1000 // 60 seconds for user data refresh
|
||||
const TOKEN_REFRESH_BUFFER = 120 * 1000 // 120 seconds before expiry to refresh token
|
||||
|
||||
export const useAuthStore = defineStore('auth', () => {
|
||||
// ==================== State ====================
|
||||
|
||||
const user = ref<User | null>(null)
|
||||
const token = ref<string | null>(null)
|
||||
const refreshTokenValue = ref<string | null>(null)
|
||||
const tokenExpiresAt = ref<number | null>(null) // 过期时间戳(毫秒)
|
||||
const runMode = ref<'standard' | 'simple'>('standard')
|
||||
let refreshIntervalId: ReturnType<typeof setInterval> | null = null
|
||||
let tokenRefreshTimeoutId: ReturnType<typeof setTimeout> | null = null
|
||||
|
||||
// ==================== Computed ====================
|
||||
|
||||
@@ -42,19 +48,29 @@ export const useAuthStore = defineStore('auth', () => {
|
||||
function checkAuth(): void {
|
||||
const savedToken = localStorage.getItem(AUTH_TOKEN_KEY)
|
||||
const savedUser = localStorage.getItem(AUTH_USER_KEY)
|
||||
const savedRefreshToken = localStorage.getItem(REFRESH_TOKEN_KEY)
|
||||
const savedExpiresAt = localStorage.getItem(TOKEN_EXPIRES_AT_KEY)
|
||||
|
||||
if (savedToken && savedUser) {
|
||||
try {
|
||||
token.value = savedToken
|
||||
user.value = JSON.parse(savedUser)
|
||||
refreshTokenValue.value = savedRefreshToken
|
||||
tokenExpiresAt.value = savedExpiresAt ? parseInt(savedExpiresAt, 10) : null
|
||||
|
||||
// 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
|
||||
// Start auto-refresh interval for user data
|
||||
startAutoRefresh()
|
||||
|
||||
// Start proactive token refresh if we have refresh token and expiry info
|
||||
// Note: use !== null to handle case when tokenExpiresAt.value is 0 (expired)
|
||||
if (savedRefreshToken && tokenExpiresAt.value !== null) {
|
||||
scheduleTokenRefreshAt(tokenExpiresAt.value)
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to parse saved user data:', error)
|
||||
clearAuth()
|
||||
@@ -89,6 +105,76 @@ export const useAuthStore = defineStore('auth', () => {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Schedule proactive token refresh before expiry (based on expiry timestamp)
|
||||
* @param expiresAtMs - Token expiry timestamp in milliseconds
|
||||
*/
|
||||
function scheduleTokenRefreshAt(expiresAtMs: number): void {
|
||||
// Clear any existing timeout
|
||||
if (tokenRefreshTimeoutId) {
|
||||
clearTimeout(tokenRefreshTimeoutId)
|
||||
tokenRefreshTimeoutId = null
|
||||
}
|
||||
|
||||
// Calculate remaining time until refresh (buffer time before expiry)
|
||||
const now = Date.now()
|
||||
const refreshInMs = Math.max(0, expiresAtMs - now - TOKEN_REFRESH_BUFFER)
|
||||
|
||||
if (refreshInMs <= 0) {
|
||||
// Token is about to expire or already expired, refresh immediately
|
||||
performTokenRefresh()
|
||||
return
|
||||
}
|
||||
|
||||
tokenRefreshTimeoutId = setTimeout(() => {
|
||||
performTokenRefresh()
|
||||
}, refreshInMs)
|
||||
}
|
||||
|
||||
/**
|
||||
* Schedule proactive token refresh before expiry (based on expires_in seconds)
|
||||
* @param expiresInSeconds - Token expiry time in seconds from now
|
||||
*/
|
||||
function scheduleTokenRefresh(expiresInSeconds: number): void {
|
||||
const expiresAtMs = Date.now() + expiresInSeconds * 1000
|
||||
tokenExpiresAt.value = expiresAtMs
|
||||
localStorage.setItem(TOKEN_EXPIRES_AT_KEY, String(expiresAtMs))
|
||||
scheduleTokenRefreshAt(expiresAtMs)
|
||||
}
|
||||
|
||||
/**
|
||||
* Perform the actual token refresh
|
||||
*/
|
||||
async function performTokenRefresh(): Promise<void> {
|
||||
if (!refreshTokenValue.value) {
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await authAPI.refreshToken()
|
||||
|
||||
// Update state
|
||||
token.value = response.access_token
|
||||
refreshTokenValue.value = response.refresh_token
|
||||
|
||||
// Schedule next refresh (this also updates tokenExpiresAt and localStorage)
|
||||
scheduleTokenRefresh(response.expires_in)
|
||||
} catch (error) {
|
||||
console.error('Token refresh failed:', error)
|
||||
// Don't clear auth here - the interceptor will handle 401 errors
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Stop token refresh timeout
|
||||
*/
|
||||
function stopTokenRefresh(): void {
|
||||
if (tokenRefreshTimeoutId) {
|
||||
clearTimeout(tokenRefreshTimeoutId)
|
||||
tokenRefreshTimeoutId = null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* User login
|
||||
* @param credentials - Login credentials (email and password)
|
||||
@@ -141,6 +227,12 @@ export const useAuthStore = defineStore('auth', () => {
|
||||
// Store token and user
|
||||
token.value = response.access_token
|
||||
|
||||
// Store refresh token if present
|
||||
if (response.refresh_token) {
|
||||
refreshTokenValue.value = response.refresh_token
|
||||
localStorage.setItem(REFRESH_TOKEN_KEY, response.refresh_token)
|
||||
}
|
||||
|
||||
// Extract run_mode if present
|
||||
if (response.user.run_mode) {
|
||||
runMode.value = response.user.run_mode
|
||||
@@ -152,8 +244,14 @@ export const useAuthStore = defineStore('auth', () => {
|
||||
localStorage.setItem(AUTH_TOKEN_KEY, response.access_token)
|
||||
localStorage.setItem(AUTH_USER_KEY, JSON.stringify(userData))
|
||||
|
||||
// Start auto-refresh interval
|
||||
// Start auto-refresh interval for user data
|
||||
startAutoRefresh()
|
||||
|
||||
// Start proactive token refresh if we have refresh token and expiry info
|
||||
// scheduleTokenRefresh will also store the expiry timestamp
|
||||
if (response.refresh_token && response.expires_in) {
|
||||
scheduleTokenRefresh(response.expires_in)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -166,24 +264,10 @@ export const useAuthStore = defineStore('auth', () => {
|
||||
try {
|
||||
const response = await authAPI.register(userData)
|
||||
|
||||
// Store token and user
|
||||
token.value = response.access_token
|
||||
// Use the common helper to set auth state
|
||||
setAuthFromResponse(response)
|
||||
|
||||
// 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
|
||||
return user.value!
|
||||
} catch (error) {
|
||||
// Clear any partial state on error
|
||||
clearAuth()
|
||||
@@ -193,18 +277,41 @@ export const useAuthStore = defineStore('auth', () => {
|
||||
|
||||
/**
|
||||
* 直接设置 token(用于 OAuth/SSO 回调),并加载当前用户信息。
|
||||
* 会自动读取 localStorage 中已设置的 refresh_token 和 token_expires_in
|
||||
* @param newToken - 后端签发的 JWT access token
|
||||
*/
|
||||
async function setToken(newToken: string): Promise<User> {
|
||||
// Clear any previous state first (avoid mixing sessions)
|
||||
clearAuth()
|
||||
// Note: Don't clear localStorage here as OAuth callback may have set refresh_token
|
||||
stopAutoRefresh()
|
||||
stopTokenRefresh()
|
||||
token.value = null
|
||||
user.value = null
|
||||
|
||||
token.value = newToken
|
||||
localStorage.setItem(AUTH_TOKEN_KEY, newToken)
|
||||
|
||||
// Read refresh token and expires_at from localStorage if set by OAuth callback
|
||||
const savedRefreshToken = localStorage.getItem(REFRESH_TOKEN_KEY)
|
||||
const savedExpiresAt = localStorage.getItem(TOKEN_EXPIRES_AT_KEY)
|
||||
|
||||
if (savedRefreshToken) {
|
||||
refreshTokenValue.value = savedRefreshToken
|
||||
}
|
||||
if (savedExpiresAt) {
|
||||
tokenExpiresAt.value = parseInt(savedExpiresAt, 10)
|
||||
}
|
||||
|
||||
try {
|
||||
const userData = await refreshUser()
|
||||
startAutoRefresh()
|
||||
|
||||
// Start proactive token refresh if we have refresh token and expiry info
|
||||
// Note: use !== null to handle case when tokenExpiresAt.value is 0 (expired)
|
||||
if (savedRefreshToken && tokenExpiresAt.value !== null) {
|
||||
scheduleTokenRefreshAt(tokenExpiresAt.value)
|
||||
}
|
||||
|
||||
return userData
|
||||
} catch (error) {
|
||||
clearAuth()
|
||||
@@ -216,9 +323,9 @@ export const useAuthStore = defineStore('auth', () => {
|
||||
* User logout
|
||||
* Clears all authentication state and persisted data
|
||||
*/
|
||||
function logout(): void {
|
||||
// Call API logout (client-side cleanup)
|
||||
authAPI.logout()
|
||||
async function logout(): Promise<void> {
|
||||
// Call API logout (revokes refresh token on server)
|
||||
await authAPI.logout()
|
||||
|
||||
// Clear state
|
||||
clearAuth()
|
||||
@@ -263,11 +370,17 @@ export const useAuthStore = defineStore('auth', () => {
|
||||
function clearAuth(): void {
|
||||
// Stop auto-refresh
|
||||
stopAutoRefresh()
|
||||
// Stop token refresh
|
||||
stopTokenRefresh()
|
||||
|
||||
token.value = null
|
||||
refreshTokenValue.value = null
|
||||
tokenExpiresAt.value = null
|
||||
user.value = null
|
||||
localStorage.removeItem(AUTH_TOKEN_KEY)
|
||||
localStorage.removeItem(AUTH_USER_KEY)
|
||||
localStorage.removeItem(REFRESH_TOKEN_KEY)
|
||||
localStorage.removeItem(TOKEN_EXPIRES_AT_KEY)
|
||||
}
|
||||
|
||||
// ==================== Return Store API ====================
|
||||
|
||||
@@ -92,6 +92,8 @@ export interface PublicSettings {
|
||||
|
||||
export interface AuthResponse {
|
||||
access_token: string
|
||||
refresh_token?: string // New: Refresh Token for token renewal
|
||||
expires_in?: number // New: Access Token expiry time in seconds
|
||||
token_type: string
|
||||
user: User & { run_mode?: 'standard' | 'simple' }
|
||||
}
|
||||
|
||||
@@ -71,6 +71,8 @@ onMounted(async () => {
|
||||
const params = parseFragmentParams()
|
||||
|
||||
const token = params.get('access_token') || ''
|
||||
const refreshToken = params.get('refresh_token') || ''
|
||||
const expiresInStr = params.get('expires_in') || ''
|
||||
const redirect = sanitizeRedirectPath(
|
||||
params.get('redirect') || (route.query.redirect as string | undefined) || '/dashboard'
|
||||
)
|
||||
@@ -92,6 +94,17 @@ onMounted(async () => {
|
||||
}
|
||||
|
||||
try {
|
||||
// Store refresh token and expires_at (convert to timestamp) if provided
|
||||
if (refreshToken) {
|
||||
localStorage.setItem('refresh_token', refreshToken)
|
||||
}
|
||||
if (expiresInStr) {
|
||||
const expiresIn = parseInt(expiresInStr, 10)
|
||||
if (!isNaN(expiresIn)) {
|
||||
localStorage.setItem('token_expires_at', String(Date.now() + expiresIn * 1000))
|
||||
}
|
||||
}
|
||||
|
||||
await authStore.setToken(token)
|
||||
appStore.showSuccess(t('auth.loginSuccess'))
|
||||
await router.replace(redirect)
|
||||
|
||||
Reference in New Issue
Block a user