mirror of
https://github.com/fawney19/Aether.git
synced 2026-09-01 17:00:21 +08:00
feat(auth): 重构认证系统,引入 session 会话管理
- 新增 user_sessions 数据库表及 Alembic 迁移 - 实现 SessionService 会话生命周期管理(创建/刷新/撤销/清理) - 认证流程改用 refresh token cookie + access token 双令牌模式 - 前端实现自动静默刷新、跨标签页同步及设备指纹 - 用户设置页新增会话管理和密码修改功能 - 管理员用户管理新增强制登出和会话查看 - 密码策略增强,支持强度校验和泄露检测 - OAuth 登录流程适配新会话机制 - 新增完整的单元测试和 API 测试覆盖 Closes #232 Co-authored-by: LewisPen <LewisPen@nyadoo.com>
This commit is contained in:
@@ -5,12 +5,14 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { onMounted, onErrorCaptured } from 'vue'
|
||||
import { onMounted, onErrorCaptured, onUnmounted } from 'vue'
|
||||
import { useAuthStore } from '@/stores/auth'
|
||||
import ToastContainer from '@/components/ToastContainer.vue'
|
||||
import ConfirmContainer from '@/components/ConfirmContainer.vue'
|
||||
import apiClient from '@/api/client'
|
||||
import apiClient, { AUTH_STATE_CHANGE_EVENT } from '@/api/client'
|
||||
import { NETWORK_CONFIG, AUTH_CONFIG } from '@/config/constants'
|
||||
import router from '@/router'
|
||||
import { hasAuthIdentityChanged } from '@/utils/authToken'
|
||||
import { log } from '@/utils/logger'
|
||||
|
||||
const authStore = useAuthStore()
|
||||
@@ -86,7 +88,59 @@ if (typeof window !== 'undefined') {
|
||||
})
|
||||
}
|
||||
|
||||
async function syncExternalAuthState(nextToken: string | null): Promise<void> {
|
||||
const previousToken = authStore.token
|
||||
const previousUser = authStore.user
|
||||
? {
|
||||
id: authStore.user.id,
|
||||
role: authStore.user.role,
|
||||
}
|
||||
: null
|
||||
|
||||
authStore.syncToken()
|
||||
|
||||
if (!nextToken) {
|
||||
if (previousToken || previousUser) {
|
||||
authStore.applyExternalLogout()
|
||||
await router.replace('/')
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
const identityChanged = hasAuthIdentityChanged(previousToken, nextToken, previousUser)
|
||||
if (!identityChanged && previousUser) {
|
||||
return
|
||||
}
|
||||
|
||||
const user = await authStore.fetchCurrentUser()
|
||||
if (!user) {
|
||||
return
|
||||
}
|
||||
|
||||
if (router.currentRoute.value.path.startsWith('/admin') && user.role !== 'admin') {
|
||||
await router.replace('/dashboard')
|
||||
}
|
||||
}
|
||||
|
||||
function handleAuthStorageChange(event: StorageEvent): void {
|
||||
if (event.key !== 'access_token') {
|
||||
return
|
||||
}
|
||||
|
||||
syncExternalAuthState(event.newValue).catch((err) => log.error('syncExternalAuthState failed', err))
|
||||
}
|
||||
|
||||
function handleLocalAuthStateChange(event: Event): void {
|
||||
const authEvent = event as CustomEvent<{ token: string | null }>
|
||||
syncExternalAuthState(authEvent.detail?.token ?? apiClient.getToken()).catch((err) => log.error('syncExternalAuthState failed', err))
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
if (typeof window !== 'undefined') {
|
||||
window.addEventListener('storage', handleAuthStorageChange)
|
||||
window.addEventListener(AUTH_STATE_CHANGE_EVENT, handleLocalAuthStateChange as (event: Event) => void)
|
||||
}
|
||||
|
||||
// 延迟检查认证状态,让页面先加载
|
||||
setTimeout(async () => {
|
||||
try {
|
||||
@@ -97,4 +151,14 @@ onMounted(async () => {
|
||||
}
|
||||
}, AUTH_CONFIG.TOKEN_REFRESH_INTERVAL)
|
||||
})
|
||||
|
||||
onUnmounted(() => {
|
||||
if (typeof window !== 'undefined') {
|
||||
window.removeEventListener('storage', handleAuthStorageChange)
|
||||
window.removeEventListener(
|
||||
AUTH_STATE_CHANGE_EVENT,
|
||||
handleLocalAuthStateChange as (event: Event) => void,
|
||||
)
|
||||
}
|
||||
})
|
||||
</script>
|
||||
|
||||
31
frontend/src/api/__tests__/client.spec.ts
Normal file
31
frontend/src/api/__tests__/client.spec.ts
Normal file
@@ -0,0 +1,31 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import apiClient, { AUTH_STATE_CHANGE_EVENT } from '@/api/client'
|
||||
|
||||
describe('apiClient auth state change event', () => {
|
||||
beforeEach(() => {
|
||||
localStorage.clear()
|
||||
apiClient.clearAuth()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
localStorage.clear()
|
||||
apiClient.clearAuth()
|
||||
})
|
||||
|
||||
it('dispatches a same-tab auth change event when clearing auth', () => {
|
||||
const handler = vi.fn()
|
||||
window.addEventListener(AUTH_STATE_CHANGE_EVENT, handler as EventListener)
|
||||
|
||||
apiClient.setToken('access-token')
|
||||
apiClient.clearAuth()
|
||||
|
||||
expect(localStorage.getItem('access_token')).toBeNull()
|
||||
expect(handler).toHaveBeenCalledTimes(1)
|
||||
|
||||
const event = handler.mock.calls[0][0] as CustomEvent<{ token: string | null }>
|
||||
expect(event.detail).toEqual({ token: null })
|
||||
|
||||
window.removeEventListener(AUTH_STATE_CHANGE_EVENT, handler as EventListener)
|
||||
})
|
||||
})
|
||||
@@ -9,7 +9,6 @@ export interface LoginRequest {
|
||||
|
||||
export interface LoginResponse {
|
||||
access_token: string
|
||||
refresh_token?: string
|
||||
token_type?: string
|
||||
expires_in?: number
|
||||
user_id?: string // UUID
|
||||
@@ -127,10 +126,6 @@ export const authApi = {
|
||||
async login(credentials: LoginRequest): Promise<LoginResponse> {
|
||||
const response = await apiClient.post<LoginResponse>('/api/auth/login', credentials)
|
||||
apiClient.setToken(response.data.access_token)
|
||||
// 后端暂时没有返回 refresh_token
|
||||
if (response.data.refresh_token) {
|
||||
localStorage.setItem('refresh_token', response.data.refresh_token)
|
||||
}
|
||||
return response.data
|
||||
},
|
||||
|
||||
@@ -152,14 +147,9 @@ export const authApi = {
|
||||
return response.data
|
||||
},
|
||||
|
||||
async refreshToken(refreshToken: string): Promise<LoginResponse> {
|
||||
const response = await apiClient.post<LoginResponse>('/api/auth/refresh', {
|
||||
refresh_token: refreshToken
|
||||
})
|
||||
async refreshToken(): Promise<LoginResponse> {
|
||||
const response = await apiClient.post<LoginResponse>('/api/auth/refresh', {})
|
||||
apiClient.setToken(response.data.access_token)
|
||||
if (response.data.refresh_token) {
|
||||
localStorage.setItem('refresh_token', response.data.refresh_token)
|
||||
}
|
||||
return response.data
|
||||
},
|
||||
|
||||
|
||||
@@ -3,10 +3,13 @@ import type { AxiosInstance, AxiosRequestConfig, AxiosResponse, InternalAxiosReq
|
||||
import { NETWORK_CONFIG, AUTH_CONFIG } from '@/config/constants'
|
||||
import { isDemoMode } from '@/config/demo'
|
||||
import { handleMockRequest, setMockUserToken } from '@/mocks'
|
||||
import { getClientDeviceId } from '@/utils/deviceId'
|
||||
import { CrossTabRefreshCoordinator } from '@/utils/crossTabRefresh'
|
||||
import { log } from '@/utils/logger'
|
||||
|
||||
// 在开发环境下使用代理,生产环境使用环境变量
|
||||
const API_BASE_URL = import.meta.env.VITE_API_URL || ''
|
||||
export const AUTH_STATE_CHANGE_EVENT = 'aether-auth-state-change'
|
||||
|
||||
/**
|
||||
* 判断请求是否为公共端点
|
||||
@@ -31,17 +34,15 @@ function isAuthRequest(url?: string): boolean {
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断是否为可刷新的认证错误
|
||||
* 判断 403 错误是否表示用户账号级别的问题(需要清除认证并跳转)
|
||||
*/
|
||||
function isRefreshableAuthError(errorDetail: string): boolean {
|
||||
const nonRefreshableErrors = [
|
||||
function isAccountLevelForbidden(status: number, errorDetail: string): boolean {
|
||||
if (status !== 403) return false
|
||||
const accountErrors = [
|
||||
'用户不存在或已禁用',
|
||||
'需要管理员权限',
|
||||
'权限不足',
|
||||
'用户已禁用',
|
||||
]
|
||||
|
||||
return !nonRefreshableErrors.some((msg) => errorDetail.includes(msg))
|
||||
return accountErrors.some((msg) => errorDetail.includes(msg))
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -83,12 +84,21 @@ class ApiClient {
|
||||
private client: AxiosInstance
|
||||
private token: string | null = null
|
||||
private isRefreshing = false
|
||||
private refreshPromise: Promise<AxiosResponse> | null = null
|
||||
private refreshPromise: Promise<string> | null = null
|
||||
private readonly refreshCoordinator = new CrossTabRefreshCoordinator()
|
||||
|
||||
private readonly onStorageSync = (event: StorageEvent): void => {
|
||||
if (event.key !== 'access_token') {
|
||||
return
|
||||
}
|
||||
this.syncTokenState(event.newValue)
|
||||
}
|
||||
|
||||
constructor() {
|
||||
this.client = axios.create({
|
||||
baseURL: API_BASE_URL,
|
||||
timeout: NETWORK_CONFIG.API_TIMEOUT,
|
||||
withCredentials: true,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
@@ -99,6 +109,7 @@ class ApiClient {
|
||||
this.client.defaults.adapter = createDemoAdapter(defaultAdapter)
|
||||
|
||||
this.setupInterceptors()
|
||||
this.setupCrossTabAuthSync()
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -108,6 +119,10 @@ class ApiClient {
|
||||
// 请求拦截器 - 仅处理认证
|
||||
this.client.interceptors.request.use(
|
||||
(config) => {
|
||||
if (config.url?.includes('/api/')) {
|
||||
config.headers['X-Client-Device-Id'] = getClientDeviceId()
|
||||
}
|
||||
|
||||
const requiresAuth = !isPublicEndpoint(config.url, config.method) &&
|
||||
config.url?.includes('/api/')
|
||||
|
||||
@@ -129,6 +144,23 @@ class ApiClient {
|
||||
)
|
||||
}
|
||||
|
||||
private setupCrossTabAuthSync(): void {
|
||||
if (typeof window !== 'undefined') {
|
||||
window.addEventListener('storage', this.onStorageSync)
|
||||
}
|
||||
}
|
||||
|
||||
private emitAuthStateChange(token: string | null): void {
|
||||
if (typeof window === 'undefined') {
|
||||
return
|
||||
}
|
||||
window.dispatchEvent(
|
||||
new CustomEvent<{ token: string | null }>(AUTH_STATE_CHANGE_EVENT, {
|
||||
detail: { token },
|
||||
})
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理响应错误
|
||||
*/
|
||||
@@ -155,8 +187,22 @@ class ApiClient {
|
||||
return Promise.reject(error)
|
||||
}
|
||||
|
||||
const status = error.response?.status ?? 0
|
||||
|
||||
// 处理 403 用户账号级别错误(被禁用/删除)
|
||||
if (status === 403) {
|
||||
const rawDetail = (error.response?.data as Record<string, unknown>)?.detail
|
||||
const errorDetail = typeof rawDetail === 'string' ? rawDetail : ''
|
||||
if (isAccountLevelForbidden(status, errorDetail)) {
|
||||
log.info('User account issue detected, clearing auth', { errorDetail })
|
||||
this.clearAuth()
|
||||
window.location.href = '/'
|
||||
return Promise.reject(error)
|
||||
}
|
||||
}
|
||||
|
||||
// 处理401错误
|
||||
if (error.response?.status === 401) {
|
||||
if (status === 401) {
|
||||
return this.handle401Error(error, originalRequest)
|
||||
}
|
||||
|
||||
@@ -177,25 +223,7 @@ class ApiClient {
|
||||
return Promise.reject(error)
|
||||
}
|
||||
|
||||
const errorDetail = (error.response?.data as Record<string, unknown>)?.detail as string || ''
|
||||
log.debug('Got 401 error, attempting token refresh', { errorDetail })
|
||||
|
||||
// 检查是否为业务相关的401错误(用户被禁用/删除等)
|
||||
if (!isRefreshableAuthError(errorDetail)) {
|
||||
log.info('User account issue detected, logging out and redirecting to home', { errorDetail })
|
||||
this.clearAuth()
|
||||
// 跳转到首页
|
||||
window.location.href = '/'
|
||||
return Promise.reject(error)
|
||||
}
|
||||
|
||||
// 获取refresh token
|
||||
const refreshToken = localStorage.getItem('refresh_token')
|
||||
if (!refreshToken) {
|
||||
log.info('No refresh token available, clearing invalid token')
|
||||
this.clearAuth()
|
||||
return Promise.reject(error)
|
||||
}
|
||||
log.debug('Got 401 error, attempting token refresh')
|
||||
|
||||
// 标记为已重试
|
||||
originalRequest._retry = true
|
||||
@@ -210,8 +238,8 @@ class ApiClient {
|
||||
// 如果正在刷新,等待刷新完成
|
||||
if (this.isRefreshing) {
|
||||
try {
|
||||
await this.refreshPromise
|
||||
originalRequest.headers.Authorization = `Bearer ${this.getToken()}`
|
||||
const accessToken = await this.refreshPromise
|
||||
originalRequest.headers.Authorization = `Bearer ${accessToken}`
|
||||
return this.client.request(originalRequest)
|
||||
} catch {
|
||||
return Promise.reject(error)
|
||||
@@ -219,29 +247,27 @@ class ApiClient {
|
||||
}
|
||||
|
||||
// 开始刷新token
|
||||
return this.refreshTokenAndRetry(refreshToken, originalRequest, error)
|
||||
return this.refreshTokenAndRetry(originalRequest, error)
|
||||
}
|
||||
|
||||
/**
|
||||
* 刷新token并重试原始请求
|
||||
*/
|
||||
private async refreshTokenAndRetry(
|
||||
refreshToken: string,
|
||||
originalRequest: InternalAxiosRequestConfig,
|
||||
originalError: import('axios').AxiosError
|
||||
): Promise<AxiosResponse> {
|
||||
this.isRefreshing = true
|
||||
this.refreshPromise = this.refreshToken(refreshToken)
|
||||
this.refreshPromise = this.coordinatedRefresh()
|
||||
|
||||
try {
|
||||
const response = await this.refreshPromise
|
||||
this.setToken(response.data.access_token)
|
||||
localStorage.setItem('refresh_token', response.data.refresh_token)
|
||||
const accessToken = await this.refreshPromise
|
||||
this.setToken(accessToken)
|
||||
this.isRefreshing = false
|
||||
this.refreshPromise = null
|
||||
|
||||
// 重试原始请求
|
||||
originalRequest.headers.Authorization = `Bearer ${response.data.access_token}`
|
||||
originalRequest.headers.Authorization = `Bearer ${accessToken}`
|
||||
return this.client.request(originalRequest)
|
||||
} catch (refreshError: unknown) {
|
||||
log.error('Token refresh failed', refreshError instanceof Error ? refreshError.message : String(refreshError))
|
||||
@@ -252,15 +278,29 @@ class ApiClient {
|
||||
}
|
||||
}
|
||||
|
||||
setToken(token: string): void {
|
||||
private async coordinatedRefresh(): Promise<string> {
|
||||
return this.refreshCoordinator.run(async () => {
|
||||
const response = await this.refreshToken()
|
||||
const accessToken = response.data.access_token
|
||||
if (!accessToken) {
|
||||
throw new Error('Refresh response missing access token')
|
||||
}
|
||||
return accessToken
|
||||
})
|
||||
}
|
||||
|
||||
private syncTokenState(token: string | null): void {
|
||||
this.token = token
|
||||
localStorage.setItem('access_token', token)
|
||||
// 同步到 mock handler
|
||||
if (isDemoMode()) {
|
||||
setMockUserToken(token)
|
||||
}
|
||||
}
|
||||
|
||||
setToken(token: string): void {
|
||||
this.syncTokenState(token)
|
||||
localStorage.setItem('access_token', token)
|
||||
}
|
||||
|
||||
getToken(): string | null {
|
||||
if (!this.token) {
|
||||
this.token = localStorage.getItem('access_token')
|
||||
@@ -273,18 +313,17 @@ class ApiClient {
|
||||
}
|
||||
|
||||
clearAuth(): void {
|
||||
this.token = null
|
||||
const hadAuth = this.token !== null || localStorage.getItem('access_token') !== null
|
||||
this.syncTokenState(null)
|
||||
localStorage.removeItem('access_token')
|
||||
localStorage.removeItem('refresh_token')
|
||||
// 同步清除 mock token
|
||||
if (isDemoMode()) {
|
||||
setMockUserToken(null)
|
||||
// 同标签页内清理认证状态时不会触发 storage 事件,这里主动广播一次。
|
||||
if (hadAuth) {
|
||||
this.emitAuthStateChange(null)
|
||||
}
|
||||
}
|
||||
|
||||
async refreshToken(refreshToken: string): Promise<AxiosResponse> {
|
||||
// refreshToken 会通过 adapter 处理 Demo 模式
|
||||
return this.client.post('/api/auth/refresh', { refresh_token: refreshToken })
|
||||
async refreshToken(): Promise<AxiosResponse> {
|
||||
return this.client.post('/api/auth/refresh', {})
|
||||
}
|
||||
|
||||
// 以下方法直接委托给 axios client,Demo 模式由 adapter 统一处理
|
||||
|
||||
@@ -3,6 +3,9 @@ import type { ActivityHeatmap } from '@/types/activity'
|
||||
import type { TieredPricingConfig } from './endpoints/types'
|
||||
import { cachedRequest, buildCacheKey } from '@/utils/cache'
|
||||
import type { BillingSummary } from './auth'
|
||||
import type { UserSession } from '@/types/session'
|
||||
|
||||
export type { UserSession }
|
||||
|
||||
export interface Profile {
|
||||
id: string // UUID
|
||||
@@ -176,6 +179,28 @@ export const meApi = {
|
||||
return response.data
|
||||
},
|
||||
|
||||
async listSessions(): Promise<UserSession[]> {
|
||||
const response = await apiClient.get<UserSession[]>('/api/users/me/sessions')
|
||||
return response.data
|
||||
},
|
||||
|
||||
async updateSessionLabel(sessionId: string, deviceLabel: string): Promise<UserSession> {
|
||||
const response = await apiClient.patch<UserSession>(`/api/users/me/sessions/${sessionId}`, {
|
||||
device_label: deviceLabel,
|
||||
})
|
||||
return response.data
|
||||
},
|
||||
|
||||
async revokeSession(sessionId: string): Promise<{ message: string }> {
|
||||
const response = await apiClient.delete(`/api/users/me/sessions/${sessionId}`)
|
||||
return response.data
|
||||
},
|
||||
|
||||
async revokeOtherSessions(): Promise<{ message: string; revoked_count: number }> {
|
||||
const response = await apiClient.delete('/api/users/me/sessions/others')
|
||||
return response.data
|
||||
},
|
||||
|
||||
// API密钥管理
|
||||
async getApiKeys(): Promise<ApiKey[]> {
|
||||
const response = await apiClient.get<ApiKey[]>('/api/users/me/api-keys')
|
||||
|
||||
@@ -62,6 +62,8 @@ export interface UpsertUserApiKeyRequest {
|
||||
rate_limit?: number | null
|
||||
}
|
||||
|
||||
export type { UserSession } from '@/types/session'
|
||||
|
||||
export const usersApi = {
|
||||
async getAllUsers(): Promise<User[]> {
|
||||
const response = await apiClient.get<User[]>('/api/admin/users')
|
||||
@@ -92,6 +94,21 @@ export const usersApi = {
|
||||
return response.data.api_keys
|
||||
},
|
||||
|
||||
async getUserSessions(userId: string): Promise<UserSession[]> {
|
||||
const response = await apiClient.get<UserSession[]>(`/api/admin/users/${userId}/sessions`)
|
||||
return response.data
|
||||
},
|
||||
|
||||
async revokeUserSession(userId: string, sessionId: string): Promise<{ message: string }> {
|
||||
const response = await apiClient.delete(`/api/admin/users/${userId}/sessions/${sessionId}`)
|
||||
return response.data
|
||||
},
|
||||
|
||||
async revokeAllUserSessions(userId: string): Promise<{ message: string; revoked_count: number }> {
|
||||
const response = await apiClient.delete(`/api/admin/users/${userId}/sessions`)
|
||||
return response.data
|
||||
},
|
||||
|
||||
async createApiKey(
|
||||
userId: string,
|
||||
data: UpsertUserApiKeyRequest
|
||||
|
||||
@@ -6,7 +6,6 @@
|
||||
<input
|
||||
ref="inputRef"
|
||||
:class="inputClass"
|
||||
:style="inputStyle"
|
||||
:value="modelValue"
|
||||
:type="effectiveType"
|
||||
:autocomplete="autocompleteAttr"
|
||||
@@ -42,7 +41,6 @@
|
||||
v-else
|
||||
ref="inputRef"
|
||||
:class="inputClass"
|
||||
:style="inputStyle"
|
||||
:value="modelValue"
|
||||
:type="effectiveType"
|
||||
:autocomplete="autocompleteAttr"
|
||||
@@ -69,24 +67,6 @@ const emit = defineEmits<{
|
||||
'update:modelValue': [value: string]
|
||||
}>()
|
||||
|
||||
// 开发环境警告:type="password" 已被弃用
|
||||
const warnPasswordType = import.meta.env.DEV
|
||||
? (() => {
|
||||
let warned = false
|
||||
return () => {
|
||||
if (!warned) {
|
||||
warned = true
|
||||
// eslint-disable-next-line no-console
|
||||
console.warn(
|
||||
'[Input] type="password" 已被弃用,请使用 masked 属性代替。\n' +
|
||||
'示例:<Input v-model="apiKey" masked />\n' +
|
||||
'masked 属性使用 CSS 遮蔽而非 password 类型,不会触发浏览器密码管理器。'
|
||||
)
|
||||
}
|
||||
}
|
||||
})()
|
||||
: () => {}
|
||||
|
||||
interface Props {
|
||||
modelValue?: string | number
|
||||
class?: string
|
||||
@@ -99,9 +79,8 @@ interface Props {
|
||||
size?: 'default' | 'sm'
|
||||
/**
|
||||
* 遮蔽显示内容(用于 API Key 等敏感信息)
|
||||
* 使用 CSS -webkit-text-security 实现,不会触发浏览器密码管理器
|
||||
* 隐藏态使用真正的 password 输入框,显示态切换为 text
|
||||
* 同时会显示一个小眼睛按钮用于切换显示/隐藏
|
||||
* 注意:Firefox 不支持 -webkit-text-security,会显示明文(但仍可通过按钮切换)
|
||||
*/
|
||||
masked?: boolean
|
||||
/**
|
||||
@@ -134,13 +113,10 @@ const shouldDisableAutofill = computed(() => {
|
||||
return props.disableAutofill ?? false
|
||||
})
|
||||
|
||||
// 始终使用 text 类型,永远不用 password
|
||||
const effectiveType = computed(() => {
|
||||
const attrType = attrs.type as string | undefined
|
||||
// 如果传入 password,强制转为 text(配合 masked 使用)
|
||||
if (attrType === 'password') {
|
||||
warnPasswordType()
|
||||
return 'text'
|
||||
const attrType = (attrs.type as string | undefined) ?? 'text'
|
||||
if (props.masked) {
|
||||
return isVisible.value ? 'text' : 'password'
|
||||
}
|
||||
return attrType
|
||||
})
|
||||
@@ -182,16 +158,6 @@ const inputClass = computed(() =>
|
||||
)
|
||||
)
|
||||
|
||||
// 当 masked 为 true 且未显示时,用 CSS 遮蔽文字
|
||||
const inputStyle = computed(() => {
|
||||
if (props.masked && !isVisible.value) {
|
||||
// 使用 -webkit-text-security(Chrome, Safari, Edge 支持)
|
||||
// Firefox 不支持此属性,会显示明文,但仍可通过小眼睛按钮切换
|
||||
return { '-webkit-text-security': 'disc' }
|
||||
}
|
||||
return undefined
|
||||
})
|
||||
|
||||
function handleInput(event: Event) {
|
||||
const target = event.target as HTMLInputElement
|
||||
emit('update:modelValue', target.value)
|
||||
|
||||
@@ -247,6 +247,7 @@ import { isDemoMode, DEMO_ACCOUNTS } from '@/config/demo'
|
||||
import RegisterDialog from './RegisterDialog.vue'
|
||||
import { authApi } from '@/api/auth'
|
||||
import { oauthApi, type OAuthProviderInfo } from '@/api/oauth'
|
||||
import { getClientDeviceId } from '@/utils/deviceId'
|
||||
import { getApiUrl } from '@/utils/url'
|
||||
import { getOAuthIcon } from '@/utils/oauth-icons'
|
||||
|
||||
@@ -350,7 +351,12 @@ async function handleLogin() {
|
||||
function handleOAuthLogin(providerType: string) {
|
||||
// 如果 sessionStorage 中没有 redirectPath(用户直接点击登录而非被守卫拦截),
|
||||
// 则不设置,让 AuthCallback 使用默认跳转逻辑
|
||||
window.location.href = getApiUrl(`/api/oauth/${providerType}/authorize`)
|
||||
const authorizeUrl = new URL(
|
||||
getApiUrl(`/api/oauth/${providerType}/authorize`),
|
||||
window.location.origin,
|
||||
)
|
||||
authorizeUrl.searchParams.set('client_device_id', getClientDeviceId())
|
||||
window.location.href = authorizeUrl.toString()
|
||||
}
|
||||
|
||||
function handleSwitchToRegister() {
|
||||
|
||||
@@ -151,15 +151,12 @@
|
||||
<Input
|
||||
:id="`pwd-${formNonce}`"
|
||||
v-model="formData.password"
|
||||
type="text"
|
||||
autocomplete="one-time-code"
|
||||
data-form-type="other"
|
||||
data-lpignore="true"
|
||||
data-1p-ignore="true"
|
||||
masked
|
||||
autocomplete="new-password"
|
||||
disable-autofill
|
||||
:name="`pwd-${formNonce}`"
|
||||
:placeholder="getPasswordPolicyPlaceholder(props.passwordPolicyLevel)"
|
||||
required
|
||||
class="-webkit-text-security-disc"
|
||||
:disabled="isLoading"
|
||||
/>
|
||||
<p
|
||||
@@ -182,17 +179,20 @@
|
||||
<Input
|
||||
:id="`pwd-confirm-${formNonce}`"
|
||||
v-model="formData.confirmPassword"
|
||||
type="text"
|
||||
autocomplete="one-time-code"
|
||||
data-form-type="other"
|
||||
data-lpignore="true"
|
||||
data-1p-ignore="true"
|
||||
masked
|
||||
autocomplete="new-password"
|
||||
disable-autofill
|
||||
:name="`pwd-confirm-${formNonce}`"
|
||||
placeholder="再次输入密码"
|
||||
required
|
||||
class="-webkit-text-security-disc"
|
||||
:disabled="isLoading"
|
||||
/>
|
||||
<p
|
||||
v-if="formData.confirmPassword && formData.password !== formData.confirmPassword"
|
||||
class="text-xs text-destructive"
|
||||
>
|
||||
两次输入的密码不一致
|
||||
</p>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
|
||||
@@ -490,16 +490,15 @@ onUnmounted(() => {
|
||||
document.removeEventListener('visibilitychange', handleVisibilityChange)
|
||||
})
|
||||
|
||||
function handleRelogin() {
|
||||
async function handleRelogin() {
|
||||
showAuthError.value = false
|
||||
router.push('/').then(() => {
|
||||
authStore.logout()
|
||||
})
|
||||
await authStore.logout()
|
||||
await router.push('/')
|
||||
}
|
||||
|
||||
function handleLogout() {
|
||||
authStore.logout()
|
||||
router.push('/')
|
||||
async function handleLogout() {
|
||||
await authStore.logout()
|
||||
await router.push('/')
|
||||
}
|
||||
|
||||
function isNavActive(href: string) {
|
||||
|
||||
@@ -76,7 +76,6 @@ export const MOCK_NORMAL_USER: User = {
|
||||
|
||||
export const MOCK_LOGIN_RESPONSE_ADMIN: LoginResponse = {
|
||||
access_token: 'demo-access-token-admin',
|
||||
refresh_token: 'demo-refresh-token-admin',
|
||||
token_type: 'bearer',
|
||||
expires_in: 3600,
|
||||
user_id: MOCK_ADMIN_USER.id,
|
||||
@@ -87,7 +86,6 @@ export const MOCK_LOGIN_RESPONSE_ADMIN: LoginResponse = {
|
||||
|
||||
export const MOCK_LOGIN_RESPONSE_USER: LoginResponse = {
|
||||
access_token: 'demo-access-token-user',
|
||||
refresh_token: 'demo-refresh-token-user',
|
||||
token_type: 'bearer',
|
||||
expires_in: 3600,
|
||||
user_id: MOCK_NORMAL_USER.id,
|
||||
|
||||
@@ -531,6 +531,76 @@ const mockHandlers: Record<string, (config: AxiosRequestConfig) => Promise<Axios
|
||||
return createMockResponse({ message: '密码修改成功(演示模式)' })
|
||||
},
|
||||
|
||||
'GET /api/users/me/sessions': async () => {
|
||||
await delay()
|
||||
return createMockResponse([
|
||||
{
|
||||
id: 'session-current',
|
||||
device_label: 'Chrome / macOS',
|
||||
device_type: 'desktop',
|
||||
browser_name: 'Chrome',
|
||||
browser_version: '134.0',
|
||||
os_name: 'macOS',
|
||||
os_version: '15.3',
|
||||
device_model: null,
|
||||
ip_address: '192.168.1.100',
|
||||
last_seen_at: new Date().toISOString(),
|
||||
created_at: new Date(Date.now() - 2 * 24 * 3600 * 1000).toISOString(),
|
||||
is_current: true,
|
||||
revoked_at: null,
|
||||
revoke_reason: null
|
||||
},
|
||||
{
|
||||
id: 'session-other',
|
||||
device_label: 'Safari / iPhone',
|
||||
device_type: 'mobile',
|
||||
browser_name: 'Safari',
|
||||
browser_version: '18.0',
|
||||
os_name: 'iOS',
|
||||
os_version: '18.3',
|
||||
device_model: 'iPhone',
|
||||
ip_address: '10.0.0.12',
|
||||
last_seen_at: new Date(Date.now() - 3 * 3600 * 1000).toISOString(),
|
||||
created_at: new Date(Date.now() - 5 * 24 * 3600 * 1000).toISOString(),
|
||||
is_current: false,
|
||||
revoked_at: null,
|
||||
revoke_reason: null
|
||||
}
|
||||
])
|
||||
},
|
||||
|
||||
'DELETE /api/users/me/sessions/others': async () => {
|
||||
await delay()
|
||||
return createMockResponse({ message: '其他设备已退出登录(演示模式)', revoked_count: 1 })
|
||||
},
|
||||
|
||||
'PATCH /api/users/me/sessions/:sessionId': async (config) => {
|
||||
await delay()
|
||||
const sessionId = config.url?.split('/').pop() || 'session'
|
||||
const body = JSON.parse(config.data || '{}')
|
||||
return createMockResponse({
|
||||
id: sessionId,
|
||||
device_label: body.device_label || '已重命名设备',
|
||||
device_type: 'desktop',
|
||||
browser_name: 'Chrome',
|
||||
browser_version: '134.0',
|
||||
os_name: 'macOS',
|
||||
os_version: '15.3',
|
||||
device_model: null,
|
||||
ip_address: '192.168.1.100',
|
||||
last_seen_at: new Date().toISOString(),
|
||||
created_at: new Date(Date.now() - 2 * 24 * 3600 * 1000).toISOString(),
|
||||
is_current: sessionId === 'session-current',
|
||||
revoked_at: null,
|
||||
revoke_reason: null
|
||||
})
|
||||
},
|
||||
|
||||
'DELETE /api/users/me/sessions/:sessionId': async () => {
|
||||
await delay()
|
||||
return createMockResponse({ message: '设备已退出登录(演示模式)' })
|
||||
},
|
||||
|
||||
'GET /api/users/me/api-keys': async () => {
|
||||
await delay()
|
||||
return createMockResponse(MOCK_USER_API_KEYS)
|
||||
@@ -2086,6 +2156,44 @@ registerDynamicRoute('GET', '/api/admin/users/:userId/api-keys', async (_config,
|
||||
return createMockResponse(MOCK_USER_API_KEYS)
|
||||
})
|
||||
|
||||
// 管理员 - 用户会话列表
|
||||
registerDynamicRoute('GET', '/api/admin/users/:userId/sessions', async (_config, _params) => {
|
||||
await delay()
|
||||
requireAdmin()
|
||||
return createMockResponse([
|
||||
{
|
||||
id: 'admin-session-1',
|
||||
device_label: 'Chrome / macOS',
|
||||
device_type: 'desktop',
|
||||
browser_name: 'Chrome',
|
||||
browser_version: '134.0',
|
||||
os_name: 'macOS',
|
||||
os_version: '15.3',
|
||||
device_model: null,
|
||||
ip_address: '192.168.1.100',
|
||||
last_seen_at: new Date().toISOString(),
|
||||
created_at: new Date(Date.now() - 2 * 24 * 3600 * 1000).toISOString(),
|
||||
is_current: false,
|
||||
revoked_at: null,
|
||||
revoke_reason: null
|
||||
}
|
||||
])
|
||||
})
|
||||
|
||||
// 管理员 - 撤销用户单个会话
|
||||
registerDynamicRoute('DELETE', '/api/admin/users/:userId/sessions/:sessionId', async (_config, _params) => {
|
||||
await delay()
|
||||
requireAdmin()
|
||||
return createMockResponse({ message: '会话已撤销(演示模式)' })
|
||||
})
|
||||
|
||||
// 管理员 - 撤销用户全部会话
|
||||
registerDynamicRoute('DELETE', '/api/admin/users/:userId/sessions', async (_config, _params) => {
|
||||
await delay()
|
||||
requireAdmin()
|
||||
return createMockResponse({ message: '全部会话已撤销(演示模式)', revoked_count: 1 })
|
||||
})
|
||||
|
||||
// API Key 详情
|
||||
registerDynamicRoute('GET', '/api/admin/api-keys/:keyId', async (_config, params) => {
|
||||
await delay()
|
||||
|
||||
@@ -28,7 +28,7 @@ export async function ensureUserLoaded(
|
||||
})
|
||||
} else if (err.response?.status === 401) {
|
||||
log.info('Authentication failed, clearing session')
|
||||
authStore.logout()
|
||||
await authStore.logout()
|
||||
} else {
|
||||
log.warn('Failed to fetch user info, but keeping session', { error: err?.message })
|
||||
}
|
||||
|
||||
108
frontend/src/stores/__tests__/auth.spec.ts
Normal file
108
frontend/src/stores/__tests__/auth.spec.ts
Normal file
@@ -0,0 +1,108 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { createPinia, setActivePinia } from 'pinia'
|
||||
|
||||
const { logoutMock, getTokenMock, getCurrentUserMock } = vi.hoisted(() => ({
|
||||
logoutMock: vi.fn(),
|
||||
getTokenMock: vi.fn(() => null),
|
||||
getCurrentUserMock: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/api/auth', () => ({
|
||||
authApi: {
|
||||
logout: logoutMock,
|
||||
getCurrentUser: getCurrentUserMock,
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@/api/client', () => ({
|
||||
default: {
|
||||
getToken: getTokenMock,
|
||||
},
|
||||
}))
|
||||
|
||||
import { useAuthStore } from '@/stores/auth'
|
||||
|
||||
describe('auth store logout', () => {
|
||||
beforeEach(() => {
|
||||
setActivePinia(createPinia())
|
||||
logoutMock.mockReset()
|
||||
getTokenMock.mockReset()
|
||||
getCurrentUserMock.mockReset()
|
||||
getTokenMock.mockReturnValue(null)
|
||||
})
|
||||
|
||||
it('waits for backend logout before resolving', async () => {
|
||||
let resolveLogout: (() => void) | null = null
|
||||
logoutMock.mockImplementation(
|
||||
() =>
|
||||
new Promise<void>((resolve) => {
|
||||
resolveLogout = resolve
|
||||
})
|
||||
)
|
||||
|
||||
const store = useAuthStore()
|
||||
store.user = {
|
||||
id: 'user-1',
|
||||
username: 'tester',
|
||||
role: 'user',
|
||||
is_active: true,
|
||||
created_at: '2026-03-16T00:00:00Z',
|
||||
}
|
||||
store.token = 'access-token'
|
||||
|
||||
let settled = false
|
||||
const logoutPromise = store.logout().then(() => {
|
||||
settled = true
|
||||
})
|
||||
|
||||
await Promise.resolve()
|
||||
|
||||
expect(logoutMock).toHaveBeenCalledTimes(1)
|
||||
expect(store.user).toBeNull()
|
||||
expect(store.token).toBeNull()
|
||||
expect(settled).toBe(false)
|
||||
|
||||
resolveLogout?.()
|
||||
await logoutPromise
|
||||
|
||||
expect(settled).toBe(true)
|
||||
})
|
||||
|
||||
it('clears local auth state for external logout without calling backend', () => {
|
||||
const store = useAuthStore()
|
||||
store.user = {
|
||||
id: 'user-1',
|
||||
username: 'tester',
|
||||
role: 'user',
|
||||
is_active: true,
|
||||
created_at: '2026-03-16T00:00:00Z',
|
||||
}
|
||||
store.token = 'access-token'
|
||||
|
||||
store.applyExternalLogout()
|
||||
|
||||
expect(store.user).toBeNull()
|
||||
expect(store.token).toBeNull()
|
||||
expect(logoutMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('clears stale store auth when fetchCurrentUser fails after token was removed', async () => {
|
||||
const store = useAuthStore()
|
||||
store.user = {
|
||||
id: 'user-1',
|
||||
username: 'tester',
|
||||
role: 'user',
|
||||
is_active: true,
|
||||
created_at: '2026-03-16T00:00:00Z',
|
||||
}
|
||||
store.token = 'access-token'
|
||||
getCurrentUserMock.mockRejectedValue(new Error('unauthorized'))
|
||||
getTokenMock.mockReturnValue(null)
|
||||
|
||||
const result = await store.fetchCurrentUser()
|
||||
|
||||
expect(result).toBeNull()
|
||||
expect(store.user).toBeNull()
|
||||
expect(store.token).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -70,7 +70,13 @@ export const useAuthStore = defineStore('auth', () => {
|
||||
async function logout() {
|
||||
user.value = null
|
||||
token.value = null
|
||||
authApi.logout()
|
||||
await authApi.logout()
|
||||
}
|
||||
|
||||
function applyExternalLogout() {
|
||||
user.value = null
|
||||
token.value = null
|
||||
error.value = null
|
||||
}
|
||||
|
||||
async function fetchCurrentUser() {
|
||||
@@ -80,6 +86,10 @@ export const useAuthStore = defineStore('auth', () => {
|
||||
return userInfo
|
||||
} catch (err: unknown) {
|
||||
log.error('Failed to fetch user info', err)
|
||||
syncToken()
|
||||
if (!token.value) {
|
||||
user.value = null
|
||||
}
|
||||
// 根据用户要求,不管什么错误都不清除状态
|
||||
// 保持登录状态,除非用户手动退出
|
||||
log.info('Keeping session despite error, as per user requirement')
|
||||
@@ -106,6 +116,7 @@ export const useAuthStore = defineStore('auth', () => {
|
||||
isAdmin,
|
||||
login,
|
||||
logout,
|
||||
applyExternalLogout,
|
||||
fetchCurrentUser,
|
||||
checkAuth,
|
||||
syncToken
|
||||
|
||||
@@ -6,7 +6,8 @@ import {
|
||||
type CreateUserRequest,
|
||||
type UpdateUserRequest,
|
||||
type ApiKey,
|
||||
type UpsertUserApiKeyRequest
|
||||
type UpsertUserApiKeyRequest,
|
||||
type UserSession,
|
||||
} from '@/api/users'
|
||||
import { parseApiError } from '@/utils/errorParser'
|
||||
|
||||
@@ -131,6 +132,35 @@ export const useUsersStore = defineStore('users', () => {
|
||||
}
|
||||
}
|
||||
|
||||
async function getUserSessions(userId: string): Promise<UserSession[]> {
|
||||
try {
|
||||
return await usersApi.getUserSessions(userId)
|
||||
} catch (err: unknown) {
|
||||
error.value = parseApiError(err, '获取用户设备会话失败')
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
async function revokeUserSession(userId: string, sessionId: string): Promise<{ message: string }> {
|
||||
try {
|
||||
return await usersApi.revokeUserSession(userId, sessionId)
|
||||
} catch (err: unknown) {
|
||||
error.value = parseApiError(err, '强制下线设备失败')
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
async function revokeAllUserSessions(
|
||||
userId: string,
|
||||
): Promise<{ message: string; revoked_count: number }> {
|
||||
try {
|
||||
return await usersApi.revokeAllUserSessions(userId)
|
||||
} catch (err: unknown) {
|
||||
error.value = parseApiError(err, '强制下线全部设备失败')
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
users,
|
||||
loading,
|
||||
@@ -143,6 +173,9 @@ export const useUsersStore = defineStore('users', () => {
|
||||
createApiKey,
|
||||
updateApiKey,
|
||||
deleteApiKey,
|
||||
getFullApiKey
|
||||
getFullApiKey,
|
||||
getUserSessions,
|
||||
revokeUserSession,
|
||||
revokeAllUserSessions,
|
||||
}
|
||||
})
|
||||
|
||||
@@ -1236,10 +1236,4 @@ body[theme-mode='dark'] .literary-annotation {
|
||||
background-color: rgb(var(--color-primary-rgb) / 0.1) !important;
|
||||
}
|
||||
|
||||
/* Password masking without type="password" to prevent browser autofill */
|
||||
.-webkit-text-security-disc {
|
||||
-webkit-text-security: disc;
|
||||
-moz-text-security: disc;
|
||||
text-security: disc;
|
||||
}
|
||||
}
|
||||
|
||||
29
frontend/src/types/session.ts
Normal file
29
frontend/src/types/session.ts
Normal file
@@ -0,0 +1,29 @@
|
||||
export interface UserSession {
|
||||
id: string
|
||||
device_label: string
|
||||
device_type: string
|
||||
browser_name?: string | null
|
||||
browser_version?: string | null
|
||||
os_name?: string | null
|
||||
os_version?: string | null
|
||||
device_model?: string | null
|
||||
ip_address?: string | null
|
||||
last_seen_at?: string | null
|
||||
created_at: string
|
||||
is_current: boolean
|
||||
revoked_at?: string | null
|
||||
revoke_reason?: string | null
|
||||
}
|
||||
|
||||
export function formatSessionMeta(session: UserSession): string {
|
||||
const parts = [
|
||||
session.browser_name && session.browser_version
|
||||
? `${session.browser_name} ${session.browser_version}`
|
||||
: session.browser_name || null,
|
||||
session.os_name && session.os_version
|
||||
? `${session.os_name} ${session.os_version}`
|
||||
: session.os_name || null,
|
||||
session.device_model || null,
|
||||
].filter(Boolean)
|
||||
return parts.length > 0 ? parts.join(' \u00b7 ') : '\u8bbe\u5907\u4fe1\u606f\u672a\u77e5'
|
||||
}
|
||||
44
frontend/src/utils/__tests__/authToken.spec.ts
Normal file
44
frontend/src/utils/__tests__/authToken.spec.ts
Normal file
@@ -0,0 +1,44 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import { hasAuthIdentityChanged, parseAccessTokenIdentity } from '@/utils/authToken'
|
||||
|
||||
function buildToken(payload: Record<string, unknown>): string {
|
||||
const encoded = btoa(JSON.stringify(payload))
|
||||
.replace(/\+/g, '-')
|
||||
.replace(/\//g, '_')
|
||||
.replace(/=+$/g, '')
|
||||
return `header.${encoded}.signature`
|
||||
}
|
||||
|
||||
describe('authToken helpers', () => {
|
||||
it('parses user identity from JWT payload', () => {
|
||||
const token = buildToken({ user_id: 'user-1', role: 'admin' })
|
||||
|
||||
expect(parseAccessTokenIdentity(token)).toEqual({
|
||||
userId: 'user-1',
|
||||
role: 'admin',
|
||||
})
|
||||
})
|
||||
|
||||
it('returns null for non-jwt tokens', () => {
|
||||
expect(parseAccessTokenIdentity('demo-access-token')).toBeNull()
|
||||
})
|
||||
|
||||
it('detects unchanged identity when only token value rotates', () => {
|
||||
const previous = buildToken({ user_id: 'user-1', role: 'user', exp: 1 })
|
||||
const next = buildToken({ user_id: 'user-1', role: 'user', exp: 2 })
|
||||
|
||||
expect(
|
||||
hasAuthIdentityChanged(previous, next, { id: 'user-1', role: 'user' }),
|
||||
).toBe(false)
|
||||
})
|
||||
|
||||
it('detects account switch when user identity changes', () => {
|
||||
const previous = buildToken({ user_id: 'user-1', role: 'user' })
|
||||
const next = buildToken({ user_id: 'user-2', role: 'admin' })
|
||||
|
||||
expect(
|
||||
hasAuthIdentityChanged(previous, next, { id: 'user-1', role: 'user' }),
|
||||
).toBe(true)
|
||||
})
|
||||
})
|
||||
125
frontend/src/utils/__tests__/crossTabRefresh.spec.ts
Normal file
125
frontend/src/utils/__tests__/crossTabRefresh.spec.ts
Normal file
@@ -0,0 +1,125 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import type { BroadcastChannelLike } from '@/utils/crossTabRefresh'
|
||||
import { CrossTabRefreshCoordinator } from '@/utils/crossTabRefresh'
|
||||
|
||||
type Listener = (event: { data: unknown }) => void
|
||||
|
||||
const channelRegistry = new Map<string, Set<FakeBroadcastChannel>>()
|
||||
|
||||
class FakeBroadcastChannel implements BroadcastChannelLike {
|
||||
private readonly listeners = new Set<Listener>()
|
||||
|
||||
constructor(private readonly name: string) {
|
||||
const channels = channelRegistry.get(name) ?? new Set<FakeBroadcastChannel>()
|
||||
channels.add(this)
|
||||
channelRegistry.set(name, channels)
|
||||
}
|
||||
|
||||
postMessage(data: unknown): void {
|
||||
const channels = channelRegistry.get(this.name) ?? new Set<FakeBroadcastChannel>()
|
||||
for (const channel of channels) {
|
||||
if (channel === this) continue
|
||||
for (const listener of channel.listeners) {
|
||||
listener({ data })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
addEventListener(_type: 'message', listener: Listener): void {
|
||||
this.listeners.add(listener)
|
||||
}
|
||||
|
||||
removeEventListener(_type: 'message', listener: Listener): void {
|
||||
this.listeners.delete(listener)
|
||||
}
|
||||
|
||||
close(): void {
|
||||
channelRegistry.get(this.name)?.delete(this)
|
||||
}
|
||||
}
|
||||
|
||||
function createChannel(name: string): BroadcastChannelLike {
|
||||
return new FakeBroadcastChannel(name)
|
||||
}
|
||||
|
||||
describe('CrossTabRefreshCoordinator', () => {
|
||||
beforeEach(() => {
|
||||
localStorage.clear()
|
||||
channelRegistry.clear()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
localStorage.clear()
|
||||
channelRegistry.clear()
|
||||
})
|
||||
|
||||
it('deduplicates refresh requests across tabs', async () => {
|
||||
let resolveRefresh: ((token: string) => void) | null = null
|
||||
const firstExecutor = vi.fn(
|
||||
() =>
|
||||
new Promise<string>((resolve) => {
|
||||
resolveRefresh = resolve
|
||||
}),
|
||||
)
|
||||
const secondExecutor = vi.fn(() => Promise.resolve('should-not-run'))
|
||||
|
||||
const first = new CrossTabRefreshCoordinator({
|
||||
storage: localStorage,
|
||||
channelFactory: createChannel,
|
||||
})
|
||||
const second = new CrossTabRefreshCoordinator({
|
||||
storage: localStorage,
|
||||
channelFactory: createChannel,
|
||||
})
|
||||
|
||||
const firstRun = first.run(firstExecutor)
|
||||
await Promise.resolve()
|
||||
const secondRun = second.run(secondExecutor)
|
||||
|
||||
expect(firstExecutor).toHaveBeenCalledTimes(1)
|
||||
expect(secondExecutor).not.toHaveBeenCalled()
|
||||
|
||||
resolveRefresh?.('access-from-first-tab')
|
||||
|
||||
await expect(firstRun).resolves.toBe('access-from-first-tab')
|
||||
await expect(secondRun).resolves.toBe('access-from-first-tab')
|
||||
|
||||
first.destroy()
|
||||
second.destroy()
|
||||
})
|
||||
|
||||
it('propagates refresh failure to waiting tabs without second refresh call', async () => {
|
||||
const refreshError = new Error('refresh failed')
|
||||
let rejectRefresh: ((error: Error) => void) | null = null
|
||||
const firstExecutor = vi.fn(
|
||||
() =>
|
||||
new Promise<string>((_resolve, reject) => {
|
||||
rejectRefresh = reject
|
||||
}),
|
||||
)
|
||||
const secondExecutor = vi.fn(() => Promise.resolve('should-not-run'))
|
||||
|
||||
const first = new CrossTabRefreshCoordinator({
|
||||
storage: localStorage,
|
||||
channelFactory: createChannel,
|
||||
})
|
||||
const second = new CrossTabRefreshCoordinator({
|
||||
storage: localStorage,
|
||||
channelFactory: createChannel,
|
||||
})
|
||||
|
||||
const firstRun = first.run(firstExecutor)
|
||||
await Promise.resolve()
|
||||
const secondRun = second.run(secondExecutor)
|
||||
|
||||
rejectRefresh?.(refreshError)
|
||||
|
||||
await expect(firstRun).rejects.toThrow('refresh failed')
|
||||
await expect(secondRun).rejects.toThrow('failed in another tab')
|
||||
expect(secondExecutor).not.toHaveBeenCalled()
|
||||
|
||||
first.destroy()
|
||||
second.destroy()
|
||||
})
|
||||
})
|
||||
18
frontend/src/utils/__tests__/passwordPolicy.spec.ts
Normal file
18
frontend/src/utils/__tests__/passwordPolicy.spec.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { getPasswordPolicyErrors, validatePasswordByPolicy } from '../passwordPolicy'
|
||||
|
||||
describe('passwordPolicy utils', () => {
|
||||
it('rejects passwords longer than 72 bytes', () => {
|
||||
expect(getPasswordPolicyErrors('a'.repeat(80), 'weak')).toContain('长度不能超过72字节')
|
||||
})
|
||||
|
||||
it('rejects multibyte passwords longer than 72 bytes', () => {
|
||||
expect(getPasswordPolicyErrors('中'.repeat(25), 'weak')).toContain('长度不能超过72字节')
|
||||
})
|
||||
|
||||
it('formats validation errors into a single message', () => {
|
||||
expect(validatePasswordByPolicy('abc', 'strong')).toBe(
|
||||
'密码需要:至少 8 个字符、包含大写字母、包含数字、包含特殊字符',
|
||||
)
|
||||
})
|
||||
})
|
||||
61
frontend/src/utils/authToken.ts
Normal file
61
frontend/src/utils/authToken.ts
Normal file
@@ -0,0 +1,61 @@
|
||||
export type AccessTokenIdentity = {
|
||||
userId: string | null
|
||||
role: string | null
|
||||
}
|
||||
|
||||
function decodeBase64Url(value: string): string | null {
|
||||
try {
|
||||
const normalized = value.replace(/-/g, '+').replace(/_/g, '/')
|
||||
const padded = normalized.padEnd(Math.ceil(normalized.length / 4) * 4, '=')
|
||||
return atob(padded)
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
export function parseAccessTokenIdentity(token: string | null): AccessTokenIdentity | null {
|
||||
if (!token) {
|
||||
return null
|
||||
}
|
||||
|
||||
const parts = token.split('.')
|
||||
if (parts.length < 2) {
|
||||
return null
|
||||
}
|
||||
|
||||
const decodedPayload = decodeBase64Url(parts[1])
|
||||
if (!decodedPayload) {
|
||||
return null
|
||||
}
|
||||
|
||||
try {
|
||||
const payload = JSON.parse(decodedPayload) as Record<string, unknown>
|
||||
return {
|
||||
userId: typeof payload.user_id === 'string' ? payload.user_id : null,
|
||||
role: typeof payload.role === 'string' ? payload.role : null,
|
||||
}
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
export function hasAuthIdentityChanged(
|
||||
previousToken: string | null,
|
||||
nextToken: string | null,
|
||||
currentUser: { id?: string | null; role?: string | null } | null,
|
||||
): boolean {
|
||||
const nextIdentity = parseAccessTokenIdentity(nextToken)
|
||||
if (!nextIdentity) {
|
||||
return true
|
||||
}
|
||||
|
||||
const previousIdentity = parseAccessTokenIdentity(previousToken)
|
||||
const previousUserId = previousIdentity?.userId ?? currentUser?.id ?? null
|
||||
const previousRole = previousIdentity?.role ?? currentUser?.role ?? null
|
||||
|
||||
if (!previousUserId && !previousRole) {
|
||||
return true
|
||||
}
|
||||
|
||||
return nextIdentity.userId !== previousUserId || nextIdentity.role !== previousRole
|
||||
}
|
||||
308
frontend/src/utils/crossTabRefresh.ts
Normal file
308
frontend/src/utils/crossTabRefresh.ts
Normal file
@@ -0,0 +1,308 @@
|
||||
import { NETWORK_CONFIG } from '@/config/constants'
|
||||
|
||||
const REFRESH_LOCK_KEY = 'aether_auth_refresh_lock'
|
||||
const REFRESH_RESULT_KEY = 'aether_auth_refresh_result'
|
||||
const REFRESH_CHANNEL_NAME = 'aether-auth-refresh'
|
||||
const DEFAULT_WAIT_TIMEOUT_MS = NETWORK_CONFIG.API_TIMEOUT + 5000
|
||||
const MAX_RETRIES = 2
|
||||
|
||||
type RefreshStatus = 'success' | 'failure'
|
||||
|
||||
type RefreshLock = {
|
||||
owner: string
|
||||
requestId: string
|
||||
expiresAt: number
|
||||
}
|
||||
|
||||
type RefreshResult = {
|
||||
requestId: string
|
||||
status: RefreshStatus
|
||||
accessToken?: string
|
||||
emittedAt: number
|
||||
}
|
||||
|
||||
type RefreshEventMessage = {
|
||||
type: 'refresh-result'
|
||||
payload: RefreshResult
|
||||
}
|
||||
|
||||
type Waiter = {
|
||||
resolve: (result: RefreshResult) => void
|
||||
reject: (error: Error) => void
|
||||
timeoutId: ReturnType<typeof setTimeout>
|
||||
}
|
||||
|
||||
type BroadcastMessageEvent = {
|
||||
data: unknown
|
||||
}
|
||||
|
||||
export type BroadcastChannelLike = {
|
||||
postMessage(data: unknown): void
|
||||
addEventListener(type: 'message', listener: (event: BroadcastMessageEvent) => void): void
|
||||
removeEventListener(
|
||||
type: 'message',
|
||||
listener: (event: BroadcastMessageEvent) => void,
|
||||
): void
|
||||
close?(): void
|
||||
}
|
||||
|
||||
type CoordinatorOptions = {
|
||||
storage?: Storage | null
|
||||
waitTimeoutMs?: number
|
||||
channelFactory?: (name: string) => BroadcastChannelLike | null
|
||||
}
|
||||
|
||||
class CrossTabRefreshTimeoutError extends Error {
|
||||
constructor(requestId: string) {
|
||||
super(`Timed out while waiting for refresh request ${requestId}`)
|
||||
this.name = 'CrossTabRefreshTimeoutError'
|
||||
}
|
||||
}
|
||||
|
||||
function createId(): string {
|
||||
if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {
|
||||
return crypto.randomUUID()
|
||||
}
|
||||
return `refresh-${Math.random().toString(36).slice(2, 10)}-${Date.now()}`
|
||||
}
|
||||
|
||||
function parseJson<T>(raw: string | null): T | null {
|
||||
if (!raw) return null
|
||||
try {
|
||||
return JSON.parse(raw) as T
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
function defaultChannelFactory(name: string): BroadcastChannelLike | null {
|
||||
if (typeof BroadcastChannel === 'undefined') {
|
||||
return null
|
||||
}
|
||||
return new BroadcastChannel(name)
|
||||
}
|
||||
|
||||
export class CrossTabRefreshCoordinator {
|
||||
private readonly storage: Storage | null
|
||||
private readonly waitTimeoutMs: number
|
||||
private readonly tabId = createId()
|
||||
private readonly channel: BroadcastChannelLike | null
|
||||
private readonly waiters = new Map<string, Waiter>()
|
||||
|
||||
private readonly onStorage = (event: StorageEvent): void => {
|
||||
if (event.key !== REFRESH_RESULT_KEY || !event.newValue) {
|
||||
return
|
||||
}
|
||||
const result = parseJson<RefreshResult>(event.newValue)
|
||||
if (result) {
|
||||
this.resolveWaiter(result)
|
||||
}
|
||||
}
|
||||
|
||||
private readonly onBroadcastMessage = (event: BroadcastMessageEvent): void => {
|
||||
const message = event.data as RefreshEventMessage | null
|
||||
if (!message || message.type !== 'refresh-result') {
|
||||
return
|
||||
}
|
||||
this.resolveWaiter(message.payload)
|
||||
}
|
||||
|
||||
constructor(options: CoordinatorOptions = {}) {
|
||||
this.storage = options.storage ?? (typeof window !== 'undefined' ? window.localStorage : null)
|
||||
this.waitTimeoutMs = options.waitTimeoutMs ?? DEFAULT_WAIT_TIMEOUT_MS
|
||||
this.channel = (options.channelFactory ?? defaultChannelFactory)(REFRESH_CHANNEL_NAME)
|
||||
|
||||
if (typeof window !== 'undefined') {
|
||||
window.addEventListener('storage', this.onStorage)
|
||||
}
|
||||
this.channel?.addEventListener('message', this.onBroadcastMessage)
|
||||
}
|
||||
|
||||
destroy(): void {
|
||||
if (typeof window !== 'undefined') {
|
||||
window.removeEventListener('storage', this.onStorage)
|
||||
}
|
||||
this.channel?.removeEventListener('message', this.onBroadcastMessage)
|
||||
this.channel?.close?.()
|
||||
for (const waiter of this.waiters.values()) {
|
||||
clearTimeout(waiter.timeoutId)
|
||||
}
|
||||
this.waiters.clear()
|
||||
}
|
||||
|
||||
async run(executor: () => Promise<string>, retryCount = 0): Promise<string> {
|
||||
const activeLock = this.readActiveLock()
|
||||
if (activeLock && activeLock.owner !== this.tabId) {
|
||||
return this.waitForRefreshResult(activeLock.requestId, executor, retryCount)
|
||||
}
|
||||
|
||||
const lock = this.tryAcquireLock()
|
||||
if (!lock) {
|
||||
const currentLock = this.readActiveLock()
|
||||
if (currentLock && currentLock.owner !== this.tabId) {
|
||||
return this.waitForRefreshResult(currentLock.requestId, executor, retryCount)
|
||||
}
|
||||
return executor()
|
||||
}
|
||||
|
||||
try {
|
||||
const accessToken = await executor()
|
||||
this.publishRefreshResult({
|
||||
requestId: lock.requestId,
|
||||
status: 'success',
|
||||
accessToken,
|
||||
emittedAt: Date.now(),
|
||||
})
|
||||
return accessToken
|
||||
} catch (error) {
|
||||
this.publishRefreshResult({
|
||||
requestId: lock.requestId,
|
||||
status: 'failure',
|
||||
emittedAt: Date.now(),
|
||||
})
|
||||
throw error
|
||||
} finally {
|
||||
this.releaseLock(lock)
|
||||
}
|
||||
}
|
||||
|
||||
private waitForRefreshResult(requestId: string, executor: () => Promise<string>, retryCount: number): Promise<string> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const timeoutId = setTimeout(() => {
|
||||
this.waiters.delete(requestId)
|
||||
reject(new CrossTabRefreshTimeoutError(requestId))
|
||||
}, this.waitTimeoutMs)
|
||||
|
||||
this.waiters.set(requestId, {
|
||||
resolve: (result) => {
|
||||
if (result.status === 'success' && result.accessToken) {
|
||||
resolve(result.accessToken)
|
||||
return
|
||||
}
|
||||
reject(new Error(`Refresh request ${requestId} failed in another tab`))
|
||||
},
|
||||
reject,
|
||||
timeoutId,
|
||||
})
|
||||
}).catch((error: unknown) => {
|
||||
if (error instanceof CrossTabRefreshTimeoutError) {
|
||||
if (retryCount >= MAX_RETRIES) {
|
||||
return executor()
|
||||
}
|
||||
return this.run(executor, retryCount + 1)
|
||||
}
|
||||
throw error
|
||||
})
|
||||
}
|
||||
|
||||
private tryAcquireLock(): RefreshLock | null {
|
||||
if (!this.storage) {
|
||||
return {
|
||||
owner: this.tabId,
|
||||
requestId: createId(),
|
||||
expiresAt: Date.now() + this.waitTimeoutMs,
|
||||
}
|
||||
}
|
||||
|
||||
const existing = this.readActiveLock()
|
||||
if (existing && existing.owner !== this.tabId) {
|
||||
return null
|
||||
}
|
||||
|
||||
const lock: RefreshLock = {
|
||||
owner: this.tabId,
|
||||
requestId: createId(),
|
||||
expiresAt: Date.now() + this.waitTimeoutMs,
|
||||
}
|
||||
|
||||
try {
|
||||
// 这是一个 best-effort 跨标签页锁;写入后立刻回读,只认最终赢得竞态的 owner。
|
||||
this.storage.setItem(REFRESH_LOCK_KEY, JSON.stringify(lock))
|
||||
const current = this.readLock()
|
||||
if (current && current.owner === lock.owner && current.requestId === lock.requestId) {
|
||||
return current
|
||||
}
|
||||
} catch {
|
||||
return lock
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
private releaseLock(lock: RefreshLock): void {
|
||||
if (!this.storage) {
|
||||
return
|
||||
}
|
||||
try {
|
||||
const current = this.readLock()
|
||||
if (current && current.owner === lock.owner && current.requestId === lock.requestId) {
|
||||
this.storage.removeItem(REFRESH_LOCK_KEY)
|
||||
}
|
||||
} catch {
|
||||
// ignore storage release failures and allow lock TTL to expire naturally
|
||||
}
|
||||
}
|
||||
|
||||
private publishRefreshResult(result: RefreshResult): void {
|
||||
const message: RefreshEventMessage = {
|
||||
type: 'refresh-result',
|
||||
payload: result,
|
||||
}
|
||||
this.channel?.postMessage(message)
|
||||
if (!this.storage) {
|
||||
return
|
||||
}
|
||||
try {
|
||||
this.storage.setItem(REFRESH_RESULT_KEY, JSON.stringify(result))
|
||||
// 清理残留的 token 数据,仅依赖 BroadcastChannel 和 storage 事件的瞬时传播
|
||||
setTimeout(() => {
|
||||
try {
|
||||
this.storage?.removeItem(REFRESH_RESULT_KEY)
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}, 2000)
|
||||
} catch {
|
||||
// ignore storage publish failures; BroadcastChannel already covers most browsers
|
||||
}
|
||||
}
|
||||
|
||||
private resolveWaiter(result: RefreshResult): void {
|
||||
const waiter = this.waiters.get(result.requestId)
|
||||
if (!waiter) {
|
||||
return
|
||||
}
|
||||
clearTimeout(waiter.timeoutId)
|
||||
this.waiters.delete(result.requestId)
|
||||
waiter.resolve(result)
|
||||
}
|
||||
|
||||
private readActiveLock(): RefreshLock | null {
|
||||
const lock = this.readLock()
|
||||
if (!lock) {
|
||||
return null
|
||||
}
|
||||
if (lock.expiresAt > Date.now()) {
|
||||
return lock
|
||||
}
|
||||
if (this.storage) {
|
||||
try {
|
||||
this.storage.removeItem(REFRESH_LOCK_KEY)
|
||||
} catch {
|
||||
// ignore storage cleanup failures; stale lock will age out on next write
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
private readLock(): RefreshLock | null {
|
||||
if (!this.storage) {
|
||||
return null
|
||||
}
|
||||
try {
|
||||
return parseJson<RefreshLock>(this.storage.getItem(REFRESH_LOCK_KEY))
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
}
|
||||
19
frontend/src/utils/deviceId.ts
Normal file
19
frontend/src/utils/deviceId.ts
Normal file
@@ -0,0 +1,19 @@
|
||||
const DEVICE_ID_KEY = 'aether_client_device_id'
|
||||
|
||||
function generateDeviceId(): string {
|
||||
if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {
|
||||
return crypto.randomUUID()
|
||||
}
|
||||
return `device-${Math.random().toString(36).slice(2, 10)}-${Date.now()}`
|
||||
}
|
||||
|
||||
export function getClientDeviceId(): string {
|
||||
const existing = localStorage.getItem(DEVICE_ID_KEY)
|
||||
if (existing) {
|
||||
return existing
|
||||
}
|
||||
|
||||
const created = generateDeviceId()
|
||||
localStorage.setItem(DEVICE_ID_KEY, created)
|
||||
return created
|
||||
}
|
||||
@@ -1,4 +1,11 @@
|
||||
export type PasswordPolicyLevel = 'weak' | 'medium' | 'strong'
|
||||
export const PASSWORD_MAX_BYTES = 72
|
||||
|
||||
const textEncoder = new TextEncoder()
|
||||
|
||||
function getPasswordByteLength(password: string): number {
|
||||
return textEncoder.encode(password).length
|
||||
}
|
||||
|
||||
export const PASSWORD_POLICY_OPTIONS: Array<{
|
||||
value: PasswordPolicyLevel
|
||||
@@ -53,46 +60,51 @@ export function getPasswordPolicyPlaceholder(level: unknown): string {
|
||||
}
|
||||
}
|
||||
|
||||
export function validatePasswordByPolicy(password: string, level: unknown): string {
|
||||
if (!password) {
|
||||
return ''
|
||||
}
|
||||
/**
|
||||
* 返回所有未满足的密码策略条件。
|
||||
* 空数组 = 密码合规。
|
||||
*/
|
||||
export function getPasswordPolicyErrors(password: string, level: unknown): string[] {
|
||||
if (!password) return []
|
||||
|
||||
const normalized = normalizePasswordPolicyLevel(level)
|
||||
const errors: string[] = []
|
||||
|
||||
if (password.length < 6) {
|
||||
return '密码长度至少为6个字符'
|
||||
const byteLength = getPasswordByteLength(password)
|
||||
if (byteLength > PASSWORD_MAX_BYTES) {
|
||||
errors.push(`长度不能超过${PASSWORD_MAX_BYTES}字节`)
|
||||
}
|
||||
|
||||
// 根据策略确定最小长度,不做两段式报错
|
||||
const minLen = normalized === 'weak' ? 6 : 8
|
||||
if (password.length < minLen) {
|
||||
errors.push(`至少 ${minLen} 个字符`)
|
||||
}
|
||||
|
||||
if (normalized === 'medium') {
|
||||
if (password.length < 8) {
|
||||
return '密码长度至少为8个字符'
|
||||
}
|
||||
if (!/[A-Za-z]/.test(password)) {
|
||||
return '密码必须包含至少一个字母'
|
||||
}
|
||||
if (!/[0-9]/.test(password)) {
|
||||
return '密码必须包含至少一个数字'
|
||||
}
|
||||
if (!/[A-Za-z]/.test(password)) errors.push('包含字母')
|
||||
if (!/[0-9]/.test(password)) errors.push('包含数字')
|
||||
}
|
||||
|
||||
if (normalized === 'strong') {
|
||||
if (password.length < 8) {
|
||||
return '密码长度至少为8个字符'
|
||||
}
|
||||
if (!/[A-Z]/.test(password)) {
|
||||
return '密码必须包含至少一个大写字母'
|
||||
}
|
||||
if (!/[a-z]/.test(password)) {
|
||||
return '密码必须包含至少一个小写字母'
|
||||
}
|
||||
if (!/[0-9]/.test(password)) {
|
||||
return '密码必须包含至少一个数字'
|
||||
}
|
||||
if (!/[!@#$%^&*()_+\-=[\]{};:'",.<>?/\\|`~]/.test(password)) {
|
||||
return '密码必须包含至少一个特殊字符'
|
||||
}
|
||||
if (!/[A-Z]/.test(password)) errors.push('包含大写字母')
|
||||
if (!/[a-z]/.test(password)) errors.push('包含小写字母')
|
||||
if (!/[0-9]/.test(password)) errors.push('包含数字')
|
||||
if (!/[!@#$%^&*()_+\-=[\]{};:'",.<>?/\\|`~]/.test(password)) errors.push('包含特殊字符')
|
||||
}
|
||||
|
||||
return ''
|
||||
return errors
|
||||
}
|
||||
|
||||
/**
|
||||
* 兼容旧接口:返回单条错误字符串,空字符串表示通过。
|
||||
* 多条未满足条件时用顿号连接。
|
||||
*/
|
||||
export function validatePasswordByPolicy(password: string, level: unknown): string {
|
||||
const errors = getPasswordPolicyErrors(password, level)
|
||||
if (errors.length === 0) return ''
|
||||
if (errors.length === 1 && errors[0].startsWith('长度不能超过')) {
|
||||
return `密码${ errors[0]}`
|
||||
}
|
||||
return `密码需要:${ errors.join('、')}`
|
||||
}
|
||||
|
||||
@@ -344,6 +344,15 @@
|
||||
>
|
||||
<Key class="h-4 w-4" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
class="h-8 w-8"
|
||||
title="登录设备"
|
||||
@click="manageUserSessions(user)"
|
||||
>
|
||||
<MonitorSmartphone class="h-4 w-4" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
@@ -546,6 +555,15 @@
|
||||
<Key class="mr-1.5 h-3.5 w-3.5" />
|
||||
API Keys
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
class="h-8 text-xs"
|
||||
@click="manageUserSessions(user)"
|
||||
>
|
||||
<MonitorSmartphone class="mr-1.5 h-3.5 w-3.5" />
|
||||
设备
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
@@ -836,6 +854,94 @@
|
||||
</template>
|
||||
</Dialog>
|
||||
|
||||
<Dialog
|
||||
v-model="showUserSessionsDialog"
|
||||
size="xl"
|
||||
>
|
||||
<template #header>
|
||||
<div class="border-b border-border px-6 py-4">
|
||||
<div class="flex items-center gap-3">
|
||||
<div class="flex h-9 w-9 items-center justify-center rounded-lg bg-primary/10 flex-shrink-0">
|
||||
<MonitorSmartphone class="h-5 w-5 text-primary" />
|
||||
</div>
|
||||
<div class="flex-1 min-w-0">
|
||||
<h3 class="text-lg font-semibold text-foreground leading-tight">
|
||||
登录设备
|
||||
</h3>
|
||||
<p class="text-xs text-muted-foreground">
|
||||
查看并强制下线该用户的设备会话
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<div class="max-h-[60vh] overflow-y-auto space-y-3">
|
||||
<div
|
||||
v-if="loadingUserSessions"
|
||||
class="rounded-lg border border-dashed border-border/60 bg-muted/20 px-4 py-10 text-center text-sm text-muted-foreground"
|
||||
>
|
||||
正在加载设备会话...
|
||||
</div>
|
||||
<div
|
||||
v-else-if="userSessions.length === 0"
|
||||
class="rounded-lg border border-dashed border-border/60 bg-muted/20 px-4 py-10 text-center text-sm text-muted-foreground"
|
||||
>
|
||||
暂无在线设备
|
||||
</div>
|
||||
<div
|
||||
v-else
|
||||
class="space-y-3"
|
||||
>
|
||||
<div
|
||||
v-for="session in userSessions"
|
||||
:key="session.id"
|
||||
class="rounded-lg border border-border bg-card p-4 hover:border-primary/30 transition-colors"
|
||||
>
|
||||
<div class="flex items-center justify-between gap-3">
|
||||
<div class="min-w-0 flex-1">
|
||||
<div class="font-semibold text-foreground">
|
||||
{{ session.device_label }}
|
||||
</div>
|
||||
<div class="mt-1 text-xs text-muted-foreground">
|
||||
{{ formatSessionMeta(session) }}
|
||||
</div>
|
||||
<div class="mt-1 text-xs text-muted-foreground">
|
||||
最近活跃 {{ formatDate(session.last_seen_at || session.created_at) }}
|
||||
<span v-if="session.ip_address"> · IP {{ session.ip_address }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
:disabled="sessionDialogActionLoading === session.id"
|
||||
@click="revokeSelectedUserSession(session.id)"
|
||||
>
|
||||
{{ sessionDialogActionLoading === session.id ? '处理中...' : '强制下线' }}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<template #footer>
|
||||
<Button
|
||||
variant="outline"
|
||||
class="h-10 px-5"
|
||||
@click="showUserSessionsDialog = false"
|
||||
>
|
||||
关闭
|
||||
</Button>
|
||||
<Button
|
||||
class="h-10 px-5"
|
||||
:disabled="loadingUserSessions || userSessions.length === 0 || sessionDialogActionLoading === 'all'"
|
||||
@click="revokeAllSelectedUserSessions"
|
||||
>
|
||||
{{ sessionDialogActionLoading === 'all' ? '处理中...' : '全部下线' }}
|
||||
</Button>
|
||||
</template>
|
||||
</Dialog>
|
||||
|
||||
<WalletOpsDrawer
|
||||
:open="showWalletActionDialogState"
|
||||
:wallet="walletActionTarget?.wallet || null"
|
||||
@@ -907,7 +1013,8 @@
|
||||
<script setup lang="ts">
|
||||
import { ref, computed, onMounted, watch } from 'vue'
|
||||
import { useUsersStore } from '@/stores/users'
|
||||
import type { User, ApiKey } from '@/api/users'
|
||||
import type { User, ApiKey, UserSession } from '@/api/users'
|
||||
import { formatSessionMeta } from '@/types/session'
|
||||
import { adminWalletApi, type AdminWallet } from '@/api/admin-wallets'
|
||||
import { useToast } from '@/composables/useToast'
|
||||
import { useConfirm } from '@/composables/useConfirm'
|
||||
@@ -953,7 +1060,8 @@ import {
|
||||
Search,
|
||||
CheckCircle,
|
||||
Lock,
|
||||
LockOpen
|
||||
LockOpen,
|
||||
MonitorSmartphone
|
||||
} from 'lucide-vue-next'
|
||||
|
||||
// 功能组件
|
||||
@@ -976,12 +1084,16 @@ const userFormDialogRef = ref<InstanceType<typeof UserFormDialog>>()
|
||||
|
||||
// API Keys 对话框状态
|
||||
const showApiKeysDialog = ref(false)
|
||||
const showUserSessionsDialog = ref(false)
|
||||
const showNewApiKeyDialog = ref(false)
|
||||
const showUserApiKeyFormDialog = ref(false)
|
||||
const selectedUser = ref<User | null>(null)
|
||||
const userApiKeys = ref<ApiKey[]>([])
|
||||
const userSessions = ref<UserSession[]>([])
|
||||
const newApiKey = ref('')
|
||||
const creatingApiKey = ref(false)
|
||||
const loadingUserSessions = ref(false)
|
||||
const sessionDialogActionLoading = ref<string | null>(null)
|
||||
const apiKeyInput = ref<HTMLInputElement>()
|
||||
const editingUserApiKey = ref<ApiKey | null>(null)
|
||||
const userApiKeyForm = ref({
|
||||
@@ -1249,6 +1361,19 @@ async function manageApiKeys(user: User) {
|
||||
await loadUserApiKeys(user.id)
|
||||
}
|
||||
|
||||
async function manageUserSessions(user: User) {
|
||||
selectedUser.value = user
|
||||
showUserSessionsDialog.value = true
|
||||
loadingUserSessions.value = true
|
||||
try {
|
||||
userSessions.value = await usersStore.getUserSessions(user.id)
|
||||
} catch (err) {
|
||||
error(parseApiError(err, '加载用户设备会话失败'))
|
||||
} finally {
|
||||
loadingUserSessions.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function loadUserApiKeys(userId: string) {
|
||||
try {
|
||||
userApiKeys.value = await usersStore.getUserApiKeys(userId)
|
||||
@@ -1318,6 +1443,34 @@ async function submitUserApiKeyForm() {
|
||||
}
|
||||
}
|
||||
|
||||
async function revokeSelectedUserSession(sessionId: string) {
|
||||
if (!selectedUser.value) return
|
||||
sessionDialogActionLoading.value = sessionId
|
||||
try {
|
||||
await usersStore.revokeUserSession(selectedUser.value.id, sessionId)
|
||||
userSessions.value = userSessions.value.filter((session) => session.id !== sessionId)
|
||||
success('设备已强制下线')
|
||||
} catch (err) {
|
||||
error(parseApiError(err, '强制下线失败'))
|
||||
} finally {
|
||||
sessionDialogActionLoading.value = null
|
||||
}
|
||||
}
|
||||
|
||||
async function revokeAllSelectedUserSessions() {
|
||||
if (!selectedUser.value) return
|
||||
sessionDialogActionLoading.value = 'all'
|
||||
try {
|
||||
const result = await usersStore.revokeAllUserSessions(selectedUser.value.id)
|
||||
userSessions.value = []
|
||||
success(result.revoked_count > 0 ? `已强制下线 ${result.revoked_count} 个设备` : '没有可下线的设备')
|
||||
} catch (err) {
|
||||
error(parseApiError(err, '强制下线全部设备失败'))
|
||||
} finally {
|
||||
sessionDialogActionLoading.value = null
|
||||
}
|
||||
}
|
||||
|
||||
function selectApiKey() {
|
||||
apiKeyInput.value?.select()
|
||||
}
|
||||
|
||||
@@ -89,7 +89,6 @@ onMounted(async () => {
|
||||
const hash = window.location.hash.startsWith('#') ? window.location.hash.slice(1) : window.location.hash
|
||||
const params = new URLSearchParams(hash)
|
||||
const accessToken = params.get('access_token')
|
||||
const refreshToken = params.get('refresh_token')
|
||||
|
||||
clearUrlState()
|
||||
|
||||
@@ -101,9 +100,6 @@ onMounted(async () => {
|
||||
|
||||
hint.value = '正在写入登录态...'
|
||||
apiClient.setToken(accessToken)
|
||||
if (refreshToken) {
|
||||
localStorage.setItem('refresh_token', refreshToken)
|
||||
}
|
||||
|
||||
authStore.syncToken()
|
||||
|
||||
|
||||
@@ -117,6 +117,7 @@
|
||||
id="new-password"
|
||||
v-model="passwordForm.new_password"
|
||||
type="password"
|
||||
:placeholder="getPasswordPolicyPlaceholder(passwordPolicyLevel)"
|
||||
class="mt-1"
|
||||
/>
|
||||
<p
|
||||
@@ -138,12 +139,131 @@
|
||||
id="confirm-password"
|
||||
v-model="passwordForm.confirm_password"
|
||||
type="password"
|
||||
placeholder="再次输入密码"
|
||||
class="mt-1"
|
||||
/>
|
||||
<p
|
||||
v-if="passwordForm.confirm_password && passwordForm.new_password !== passwordForm.confirm_password"
|
||||
class="mt-1 text-xs text-destructive"
|
||||
>
|
||||
两次输入的密码不一致
|
||||
</p>
|
||||
</div>
|
||||
</form>
|
||||
</Card>
|
||||
|
||||
<Card class="p-6">
|
||||
<div class="flex items-center justify-between mb-4">
|
||||
<div>
|
||||
<h3 class="text-lg font-medium text-foreground">
|
||||
登录设备
|
||||
</h3>
|
||||
<p class="text-sm text-muted-foreground mt-1">
|
||||
管理当前账号在各设备上的登录状态
|
||||
</p>
|
||||
</div>
|
||||
<Button
|
||||
variant="outline"
|
||||
:disabled="sessionsLoading || otherSessionCount === 0 || sessionActionLoading === 'others'"
|
||||
@click="handleRevokeOtherSessions"
|
||||
>
|
||||
{{ sessionActionLoading === 'others' ? '处理中...' : '退出其他设备' }}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="sessionsLoading"
|
||||
class="text-sm text-muted-foreground"
|
||||
>
|
||||
正在加载设备列表...
|
||||
</div>
|
||||
<div
|
||||
v-else-if="userSessions.length === 0"
|
||||
class="text-sm text-muted-foreground"
|
||||
>
|
||||
暂无登录设备记录
|
||||
</div>
|
||||
<div
|
||||
v-else
|
||||
class="space-y-3"
|
||||
>
|
||||
<div
|
||||
v-for="session in userSessions"
|
||||
:key="session.id"
|
||||
class="flex items-start justify-between gap-4 rounded-lg border border-border/60 bg-muted/20 p-4"
|
||||
>
|
||||
<div class="min-w-0">
|
||||
<div class="flex items-center gap-2 flex-wrap">
|
||||
<template v-if="editingSessionId === session.id">
|
||||
<Input
|
||||
v-model="sessionLabelDraft"
|
||||
size="sm"
|
||||
class="h-8 w-56"
|
||||
maxlength="120"
|
||||
@keyup.enter="saveSessionLabel(session.id)"
|
||||
/>
|
||||
</template>
|
||||
<span
|
||||
v-else
|
||||
class="font-medium text-foreground"
|
||||
>{{ session.device_label }}</span>
|
||||
<Badge
|
||||
v-if="session.is_current"
|
||||
variant="secondary"
|
||||
>
|
||||
当前设备
|
||||
</Badge>
|
||||
</div>
|
||||
<p class="mt-1 text-xs text-muted-foreground">
|
||||
{{ formatSessionMeta(session) }}
|
||||
</p>
|
||||
<p class="mt-1 text-xs text-muted-foreground">
|
||||
最近活跃 {{ formatDate(session.last_seen_at || session.created_at) }}
|
||||
<span v-if="session.ip_address"> · IP {{ session.ip_address }}</span>
|
||||
</p>
|
||||
</div>
|
||||
<div class="flex items-center gap-2">
|
||||
<template v-if="editingSessionId === session.id">
|
||||
<Button
|
||||
size="sm"
|
||||
:disabled="sessionActionLoading === session.id || !sessionLabelDraft.trim()"
|
||||
@click="saveSessionLabel(session.id)"
|
||||
>
|
||||
{{ sessionActionLoading === session.id ? '保存中...' : '保存' }}
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
:disabled="sessionActionLoading === session.id"
|
||||
@click="cancelSessionLabelEdit"
|
||||
>
|
||||
取消
|
||||
</Button>
|
||||
</template>
|
||||
<template v-else>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
:disabled="sessionActionLoading !== null"
|
||||
@click="startSessionLabelEdit(session)"
|
||||
>
|
||||
重命名
|
||||
</Button>
|
||||
<Button
|
||||
v-if="!session.is_current"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
:disabled="sessionActionLoading === session.id"
|
||||
@click="handleRevokeSession(session.id)"
|
||||
>
|
||||
{{ sessionActionLoading === session.id ? '处理中...' : '退出' }}
|
||||
</Button>
|
||||
</template>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
<!-- OAuth 绑定 -->
|
||||
<Card class="p-6">
|
||||
<h3 class="text-lg font-medium text-foreground mb-4">
|
||||
@@ -470,15 +590,18 @@
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, computed, onMounted } from 'vue'
|
||||
import { useRoute } from 'vue-router'
|
||||
import { useRoute, useRouter } from 'vue-router'
|
||||
import { useAuthStore } from '@/stores/auth'
|
||||
import { meApi, type Profile } from '@/api/me'
|
||||
import { type UserSession, formatSessionMeta } from '@/types/session'
|
||||
import { authApi } from '@/api/auth'
|
||||
import { oauthApi, type OAuthLinkInfo, type OAuthProviderInfo } from '@/api/oauth'
|
||||
import { getClientDeviceId } from '@/utils/deviceId'
|
||||
import { getOAuthIcon } from '@/utils/oauth-icons'
|
||||
import { useDarkMode, type ThemeMode } from '@/composables/useDarkMode'
|
||||
import {
|
||||
getPasswordPolicyHint,
|
||||
getPasswordPolicyPlaceholder,
|
||||
normalizePasswordPolicyLevel,
|
||||
validatePasswordByPolicy,
|
||||
type PasswordPolicyLevel,
|
||||
@@ -503,10 +626,12 @@ import { getErrorMessage, getErrorStatus } from '@/types/api-error'
|
||||
|
||||
const authStore = useAuthStore()
|
||||
const route = useRoute()
|
||||
const router = useRouter()
|
||||
const { success, error: showError } = useToast()
|
||||
const { setThemeMode } = useDarkMode()
|
||||
|
||||
const profile = ref<Profile | null>(null)
|
||||
const userSessions = ref<UserSession[]>([])
|
||||
|
||||
const profileForm = ref({
|
||||
email: '',
|
||||
@@ -534,6 +659,10 @@ const preferencesForm = ref({
|
||||
|
||||
const savingProfile = ref(false)
|
||||
const changingPassword = ref(false)
|
||||
const sessionsLoading = ref(false)
|
||||
const sessionActionLoading = ref<string | null>(null)
|
||||
const editingSessionId = ref<string | null>(null)
|
||||
const sessionLabelDraft = ref('')
|
||||
const passwordPolicyLevel = ref<PasswordPolicyLevel>('weak')
|
||||
const themeSelectOpen = ref(false)
|
||||
const languageSelectOpen = ref(false)
|
||||
@@ -575,6 +704,8 @@ const hasPasswordChanges = computed(() => {
|
||||
}
|
||||
})
|
||||
|
||||
const otherSessionCount = computed(() => userSessions.value.filter((session) => !session.is_current).length)
|
||||
|
||||
function handleThemeChange(value: string) {
|
||||
preferencesForm.value.theme = value
|
||||
themeSelectOpen.value = false
|
||||
@@ -592,9 +723,12 @@ function handleLanguageChange(value: string) {
|
||||
|
||||
onMounted(async () => {
|
||||
await loadProfile()
|
||||
await loadPreferences()
|
||||
await loadOAuthBindings()
|
||||
await loadEmailConfigured()
|
||||
await Promise.all([
|
||||
loadPreferences(),
|
||||
loadSessions(),
|
||||
loadOAuthBindings(),
|
||||
loadEmailConfigured(),
|
||||
])
|
||||
})
|
||||
|
||||
async function loadEmailConfigured() {
|
||||
@@ -623,6 +757,23 @@ async function loadProfile() {
|
||||
}
|
||||
}
|
||||
|
||||
async function loadSessions() {
|
||||
sessionsLoading.value = true
|
||||
try {
|
||||
userSessions.value = await meApi.listSessions()
|
||||
if (editingSessionId.value) {
|
||||
const currentEditing = userSessions.value.find((session) => session.id === editingSessionId.value)
|
||||
if (!currentEditing) {
|
||||
cancelSessionLabelEdit()
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
log.error('加载登录设备失败:', error)
|
||||
} finally {
|
||||
sessionsLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function loadOAuthBindings() {
|
||||
oauthUnavailable.value = false
|
||||
oauthLinks.value = []
|
||||
@@ -670,6 +821,7 @@ function handleBind(providerType: string) {
|
||||
? new URL(basePath)
|
||||
: new URL(basePath, window.location.origin)
|
||||
bindUrl.searchParams.set('bind_token', bindToken)
|
||||
bindUrl.searchParams.set('client_device_id', getClientDeviceId())
|
||||
|
||||
// 新标签页打开 OAuth 流程
|
||||
const newTab = window.open(bindUrl.toString(), '_blank')
|
||||
@@ -804,16 +956,9 @@ async function changePassword() {
|
||||
old_password: isSettingPassword ? undefined : passwordForm.value.old_password,
|
||||
new_password: passwordForm.value.new_password
|
||||
})
|
||||
success(isSettingPassword ? '密码设置成功' : '密码修改成功')
|
||||
passwordForm.value = {
|
||||
old_password: '',
|
||||
new_password: '',
|
||||
confirm_password: ''
|
||||
}
|
||||
// 刷新 profile 以更新 has_password 状态
|
||||
if (isSettingPassword) {
|
||||
await loadProfile()
|
||||
}
|
||||
success(isSettingPassword ? '密码设置成功,请重新登录' : '密码修改成功,请重新登录')
|
||||
await authStore.logout()
|
||||
await router.replace('/')
|
||||
} catch (err) {
|
||||
log.error('修改密码失败:', err)
|
||||
const title = isSettingPassword ? '密码设置失败' : '密码修改失败'
|
||||
@@ -824,6 +969,70 @@ async function changePassword() {
|
||||
}
|
||||
}
|
||||
|
||||
function startSessionLabelEdit(session: UserSession) {
|
||||
editingSessionId.value = session.id
|
||||
sessionLabelDraft.value = session.device_label
|
||||
}
|
||||
|
||||
function cancelSessionLabelEdit() {
|
||||
editingSessionId.value = null
|
||||
sessionLabelDraft.value = ''
|
||||
}
|
||||
|
||||
async function saveSessionLabel(sessionId: string) {
|
||||
const nextLabel = sessionLabelDraft.value.trim()
|
||||
if (!nextLabel) {
|
||||
showError('设备名称不能为空')
|
||||
return
|
||||
}
|
||||
|
||||
sessionActionLoading.value = sessionId
|
||||
try {
|
||||
const updated = await meApi.updateSessionLabel(sessionId, nextLabel)
|
||||
userSessions.value = userSessions.value.map((session) =>
|
||||
session.id === sessionId ? updated : session
|
||||
)
|
||||
cancelSessionLabelEdit()
|
||||
success('设备名称已更新')
|
||||
} catch (error) {
|
||||
log.error('更新设备名称失败:', error)
|
||||
showError(getErrorMessage(error, '更新设备名称失败'))
|
||||
} finally {
|
||||
sessionActionLoading.value = null
|
||||
}
|
||||
}
|
||||
|
||||
async function handleRevokeSession(sessionId: string) {
|
||||
sessionActionLoading.value = sessionId
|
||||
try {
|
||||
await meApi.revokeSession(sessionId)
|
||||
if (editingSessionId.value === sessionId) {
|
||||
cancelSessionLabelEdit()
|
||||
}
|
||||
success('设备已退出登录')
|
||||
await loadSessions()
|
||||
} catch (error) {
|
||||
log.error('退出设备失败:', error)
|
||||
showError(getErrorMessage(error, '退出设备失败'))
|
||||
} finally {
|
||||
sessionActionLoading.value = null
|
||||
}
|
||||
}
|
||||
|
||||
async function handleRevokeOtherSessions() {
|
||||
sessionActionLoading.value = 'others'
|
||||
try {
|
||||
const result = await meApi.revokeOtherSessions()
|
||||
success(result.revoked_count > 0 ? `已退出 ${result.revoked_count} 个其他设备` : '没有其他在线设备')
|
||||
await loadSessions()
|
||||
} catch (error) {
|
||||
log.error('退出其他设备失败:', error)
|
||||
showError(getErrorMessage(error, '退出其他设备失败'))
|
||||
} finally {
|
||||
sessionActionLoading.value = null
|
||||
}
|
||||
}
|
||||
|
||||
async function updatePreferences() {
|
||||
try {
|
||||
await meApi.updatePreferences({
|
||||
|
||||
Reference in New Issue
Block a user