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:
fawney19
2026-03-17 16:34:09 +08:00
parent d480aa11f3
commit c4bb6b8161
58 changed files with 4654 additions and 508 deletions

View File

@@ -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()
}

View File

@@ -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()

View File

@@ -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({