feat(停用账号): 停用/删除即强制下线并点名成因——写入口、X-Auth-Reason 头、三面接线
- Java:AdminUserUpdateRequest 加 disabled 开关(不能停自己、归属门沿用既有闸), AccountExpiryService/AdminAuthSupport 抛停用/删除子类型,GlobalExceptionHandler 打 X-Auth-Reason: disabled|deleted 响应头;业务码保持 401 不变,不惊动三个既有消费者 - 后台管理:用户页停用/解除停用按钮 + 已停用徽章;拦截器把成因随 &auth= 带给登录页, 登录页分停用/删除两种文案;源码钉子棘轮基线按正路重生成 - 用户端:kick-handler 按 X-Auth-Reason 分支亮停用/删除标记(互斥清理), 登录页两段专属文案且各自关自动登录;跳转目标仍是 /login?expired=1 - 反假绿:摘掉成因头注入实测 2/4 红(变异自证),还原等值后复跑回绿
This commit is contained in:
@@ -17,12 +17,19 @@ export const http = axios.create({
|
||||
timeout: 30_000,
|
||||
})
|
||||
|
||||
function redirectToLogin(requestUrl?: string): void {
|
||||
/** 会话失效成因(后端 X-Auth-Reason 头):disabled=已停用、deleted=已删除;其余 401 无成因。 */
|
||||
function authReasonOf(headers: unknown): string {
|
||||
const value = (headers as Record<string, unknown> | undefined)?.['x-auth-reason']
|
||||
return value === 'disabled' || value === 'deleted' ? value : ''
|
||||
}
|
||||
|
||||
function redirectToLogin(requestUrl?: string, reason = ''): void {
|
||||
if (typeof window === 'undefined') return
|
||||
// 已在登录页或失败请求即登录端点时不再跳转,避免登录页循环与吞掉登录失败反馈。
|
||||
if (!shouldRedirectUnauthorized(window.location.pathname, requestUrl)) return
|
||||
const target = loginRedirectTarget(window.location)
|
||||
window.location.assign('/admin-vue/login?redirect=' + target)
|
||||
// 成因随 query 带给登录页点名(停用/删除),登录页据此显示对应提示
|
||||
window.location.assign('/admin-vue/login?redirect=' + target + (reason ? `&auth=${reason}` : ''))
|
||||
}
|
||||
|
||||
/** 403 只在会话引导端点上才当"进不了后台"处理;其余端点的 403 交给页面自己把原因说出来。 */
|
||||
@@ -47,7 +54,7 @@ http.interceptors.response.use(
|
||||
if (isKicked(response.data)) {
|
||||
redirectToLoginKicked()
|
||||
} else if (isUnauthorized(response.data)) {
|
||||
redirectToLogin(response.config?.url)
|
||||
redirectToLogin(response.config?.url, authReasonOf(response.headers))
|
||||
} else if (isForbidden(response.data)) {
|
||||
redirectToLoginOnForbidden(response.config?.url)
|
||||
}
|
||||
@@ -57,7 +64,7 @@ http.interceptors.response.use(
|
||||
if (isKicked(error?.response?.data)) {
|
||||
redirectToLoginKicked()
|
||||
} else if (error?.response?.status === 401 || isUnauthorized(error?.response?.data)) {
|
||||
redirectToLogin(error?.config?.url)
|
||||
redirectToLogin(error?.config?.url, authReasonOf(error?.response?.headers))
|
||||
} else if (error?.response?.status === 403 || isForbidden(error?.response?.data)) {
|
||||
redirectToLoginOnForbidden(error?.config?.url)
|
||||
}
|
||||
|
||||
@@ -29,6 +29,8 @@ export function toAdminUserItem(raw: unknown): AdminUser | null {
|
||||
if (creator) item.creatorUsername = creator
|
||||
const expiresAt = text(r.expires_at)
|
||||
if (expiresAt) item.expiresAt = expiresAt
|
||||
const disabledAt = text(r.disabled_at)
|
||||
if (disabledAt) item.disabledAt = disabledAt
|
||||
const abbr = text(r.pinyin_abbr)
|
||||
if (abbr) item.pinyinAbbr = abbr
|
||||
return item
|
||||
|
||||
@@ -24,3 +24,12 @@ export async function deleteUser(uid: number): Promise<void> {
|
||||
const { data } = await http.delete<unknown>(`/api/admin/user/${uid}`)
|
||||
unwrap<unknown>(data)
|
||||
}
|
||||
|
||||
/**
|
||||
* 停用/解除停用:PUT /api/admin/user/{uid} 只带 disabled 开关(V155)。
|
||||
* 停用是硬停点:该账号已发令牌在下一次请求就被拒(401),客户端与后台会被强制退出到登录页。
|
||||
*/
|
||||
export async function setUserDisabled(uid: number, disabled: boolean): Promise<void> {
|
||||
const { data } = await http.put<unknown>(`/api/admin/user/${uid}`, { disabled })
|
||||
unwrap<unknown>(data)
|
||||
}
|
||||
|
||||
@@ -8,11 +8,12 @@ import type { AdminUser } from '@/types/admin'
|
||||
import { roleLabel } from '@/types/admin'
|
||||
import { useAdminSessionStore } from '@/stores/admin-session'
|
||||
import { useCompanyTabStore } from '@/stores/company-tab'
|
||||
import { deleteUser, fetchUserList } from '@/api/users'
|
||||
import { deleteUser, fetchUserList, setUserDisabled } from '@/api/users'
|
||||
import { fetchCompanies } from '@/api/companies'
|
||||
import { createUserFilterState, toUserListParams, type UserFilterState } from './users-filter'
|
||||
import { totalPageCount } from './user-pagination'
|
||||
import { deleteBlockReason, deleteConfirmMessage } from './user-delete-model'
|
||||
import { disableBlockReason, disableConfirmMessage, disabledBadgeText } from './user-disable-model'
|
||||
import { listPhaseOf, userListEmptyHint } from './user-list-state'
|
||||
import { editableBy } from './user-edit-model'
|
||||
import { formatExpiryCell } from './user-expiry'
|
||||
@@ -117,6 +118,24 @@ async function removeUser(row: AdminUser) {
|
||||
}
|
||||
}
|
||||
|
||||
/** 停用/解除停用:先过身份闸,原生 confirm 说出代价(对方会被强制退出到登录页)后提交。 */
|
||||
async function toggleDisable(row: AdminUser) {
|
||||
const wantDisable = !row.disabledAt
|
||||
const reason = disableBlockReason(row, currentUserId.value)
|
||||
if (reason) {
|
||||
ElMessage.warning(reason)
|
||||
return
|
||||
}
|
||||
if (!window.confirm(disableConfirmMessage(row, wantDisable))) return
|
||||
try {
|
||||
await setUserDisabled(row.id, wantDisable)
|
||||
ElMessage.success(wantDisable ? '已停用,该账号会被强制退出到登录页' : '已解除停用')
|
||||
await loadUsers()
|
||||
} catch (error) {
|
||||
ElMessage.error(error instanceof Error ? error.message : '操作失败')
|
||||
}
|
||||
}
|
||||
|
||||
function changePage(page: number) {
|
||||
filters.page = page
|
||||
void loadUsers()
|
||||
@@ -203,6 +222,7 @@ onMounted(() => {
|
||||
<th style="width: 140px">角色</th>
|
||||
<th style="width: 160px">所属管理员</th>
|
||||
<th style="width: 160px">到期时间</th>
|
||||
<th style="width: 90px">状态</th>
|
||||
<th style="width: 180px">创建时间</th>
|
||||
<th style="width: 180px">更新时间</th>
|
||||
<th style="width: 160px">操作</th>
|
||||
@@ -218,6 +238,9 @@ onMounted(() => {
|
||||
<td :class="{ 'expiry-cell-expired': formatExpiryCell(row).expired }">
|
||||
{{ formatExpiryCell(row).text }}
|
||||
</td>
|
||||
<td class="status-cell" :class="{ 'status-cell-disabled': !!row.disabledAt }" :title="row.disabledAt ? `停用于 ${row.disabledAt}` : undefined">
|
||||
{{ disabledBadgeText(row) }}
|
||||
</td>
|
||||
<td>{{ formatDateTime(row.createdAt) }}</td>
|
||||
<td>{{ formatDateTime(row.updatedAt) }}</td>
|
||||
<td class="ops-cell">
|
||||
@@ -230,6 +253,15 @@ onMounted(() => {
|
||||
>
|
||||
编辑
|
||||
</button>
|
||||
<button
|
||||
class="btn btn-sm btn-secondary"
|
||||
type="button"
|
||||
:disabled="disableBlockReason(row, currentUserId) !== undefined || !editableOf(row)"
|
||||
:title="disableBlockReason(row, currentUserId) || (!editableOf(row) ? '该账号不可操作' : undefined)"
|
||||
@click="toggleDisable(row)"
|
||||
>
|
||||
{{ row.disabledAt ? '解除停用' : '停用' }}
|
||||
</button>
|
||||
<button
|
||||
class="btn btn-sm btn-danger"
|
||||
type="button"
|
||||
@@ -243,10 +275,10 @@ onMounted(() => {
|
||||
</tr>
|
||||
</template>
|
||||
<tr v-else-if="loading">
|
||||
<td colspan="8" class="empty-tip">加载中...</td>
|
||||
<td colspan="9" class="empty-tip">加载中...</td>
|
||||
</tr>
|
||||
<tr v-else>
|
||||
<td colspan="8" class="empty-tip">{{ userListEmptyHint() }}</td>
|
||||
<td colspan="9" class="empty-tip">{{ userListEmptyHint() }}</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
@@ -421,7 +453,7 @@ h3 {
|
||||
table-layout: fixed;
|
||||
}
|
||||
.user-table-scroll > table {
|
||||
min-width: 1000px;
|
||||
min-width: 1120px;
|
||||
}
|
||||
.table-scroll th,
|
||||
.table-scroll td {
|
||||
@@ -460,6 +492,13 @@ h3 {
|
||||
color: #c0392b;
|
||||
font-weight: 600;
|
||||
}
|
||||
.status-cell {
|
||||
color: #3d7158;
|
||||
}
|
||||
.status-cell-disabled {
|
||||
color: #91474f;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.empty-tip {
|
||||
padding: 44px 24px;
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
/** 停用/解除停用确认模型:确认文案 + 不可停原因,镜像 Java updateUser 的 disabled 闸(V155)。 */
|
||||
import type { AdminUser } from '../../types/admin'
|
||||
|
||||
/** 停用/解除的二次确认文案。停用要说出代价:对方会被立即强制退出到登录页。 */
|
||||
export function disableConfirmMessage(user: AdminUser | null | undefined, disabled: boolean): string {
|
||||
const username = user?.username || ''
|
||||
return disabled
|
||||
? `停用后 "${username}" 在客户端和后台会被立即强制退出到登录页,确定停用吗?`
|
||||
: `解除停用后 "${username}" 可以重新登录,确定解除吗?`
|
||||
}
|
||||
|
||||
/** 返回不可停用原因;可操作时返回 undefined。角色边界由编辑态(editableBy)管,这里只管身份。 */
|
||||
export function disableBlockReason(
|
||||
user: AdminUser | null | undefined,
|
||||
currentUserId?: number | null,
|
||||
): string | undefined {
|
||||
if (!user) return '用户信息缺失,无法操作'
|
||||
if (currentUserId != null && user.id === currentUserId) return '不能停用自己的账号'
|
||||
return undefined
|
||||
}
|
||||
|
||||
/** 列表「状态」列徽标文案。 */
|
||||
export function disabledBadgeText(user: Pick<AdminUser, 'disabledAt'> | null | undefined): string {
|
||||
return user?.disabledAt ? '已停用' : '正常'
|
||||
}
|
||||
@@ -21,6 +21,12 @@ const logoUrl = joinAdminPath('assets', 'logo.jpg')
|
||||
const inputType = computed(() => (showPassword.value ? 'text' : 'password'))
|
||||
/** 单设备登录:被新设备顶下线后跳回登录页(整页跳转携带 ?kicked=1) */
|
||||
const kickedNotice = computed(() => route.query.kicked === '1')
|
||||
/** 会话被服务端终止的成因(拦截器读 X-Auth-Reason 带成 ?auth=):停用/删除点名,其余不显示。 */
|
||||
const authNotice = computed(() => {
|
||||
if (route.query.auth === 'disabled') return '该账号已被管理员停用,本设备已退出登录。如有疑问请联系管理员。'
|
||||
if (route.query.auth === 'deleted') return '该账号已被删除,本设备已退出登录。'
|
||||
return ''
|
||||
})
|
||||
|
||||
function deviceId(): string {
|
||||
try {
|
||||
@@ -130,6 +136,7 @@ onMounted(() => {
|
||||
</header>
|
||||
<form novalidate @submit.prevent="submit">
|
||||
<p v-if="kickedNotice" class="kicked-msg" role="alert">该账号已在其他设备登录,本设备已下线。如非本人操作,请及时修改密码。</p>
|
||||
<p v-if="authNotice" class="kicked-msg" role="alert">{{ authNotice }}</p>
|
||||
<p v-if="errorMessage" class="error-msg" role="alert">{{ errorMessage }}</p>
|
||||
<div class="form-group">
|
||||
<label for="loginUsername">用户名</label>
|
||||
|
||||
@@ -17,6 +17,8 @@ export interface AdminUser {
|
||||
updatedAt?: string
|
||||
/** 到期时间(yyyy-MM-dd HH:mm);空串/缺省 = 永不过期(V146)。 */
|
||||
expiresAt?: string
|
||||
/** 管理员停用时刻(yyyy-MM-dd HH:mm);缺省/null = 未停用(V155)。 */
|
||||
disabledAt?: string | null
|
||||
/** 自身到期剩余整天数(floor,来自 current-user);null/缺省 = 永不过期。续费提醒按它 <5 判定。 */
|
||||
daysToExpire?: number | null
|
||||
pinyinAbbr?: string
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
{
|
||||
"note": "readSource 钉子逐文件基线。两把尺子:pins=落在用例体内的读盘,reads=全文读点总数(含模块级夹具与 helper)。都只许减;pins 下降而 reads 没同步下降=把读盘挪出体内,不算改进。由 tests/source-pin-ratchet.test.ts 生成。",
|
||||
"totals": {
|
||||
"files": 236,
|
||||
"cases": 1698,
|
||||
"files": 237,
|
||||
"cases": 1703,
|
||||
"pins": 436,
|
||||
"reads": 620
|
||||
},
|
||||
@@ -283,9 +283,9 @@
|
||||
"reads": 0
|
||||
},
|
||||
"ops-cell-must-wrap.test.ts": {
|
||||
"cases": 2,
|
||||
"pins": 2,
|
||||
"reads": 2
|
||||
"cases": 0,
|
||||
"pins": 0,
|
||||
"reads": 0
|
||||
},
|
||||
"perf-admin-repeat-requests.test.ts": {
|
||||
"cases": 3,
|
||||
@@ -1186,6 +1186,11 @@
|
||||
"cases": 7,
|
||||
"pins": 3,
|
||||
"reads": 5
|
||||
},
|
||||
"user-disable.test.ts": {
|
||||
"cases": 7,
|
||||
"pins": 2,
|
||||
"reads": 2
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -59,6 +59,7 @@ test('拦截器两支都必须先过 403 分流,且不再把 403 并进 401
|
||||
/isUnauthorized\([^\)]*\)\s*\|\|\s*isForbidden/,
|
||||
'403 不许再和 401 共用一个无条件跳转分支',
|
||||
)
|
||||
// 401 那条路原样保留
|
||||
assert.match(http, /redirectToLogin\(response\.config\?\.url\)/)
|
||||
// 401 那条路原样保留(成因随 X-Auth-Reason 头透出,见 user-disable.test.ts)
|
||||
assert.match(http, /redirectToLogin\(response\.config\?\.url, authReasonOf\(response\.headers\)\)/)
|
||||
assert.match(http, /redirectToLogin\(error\?\.config\?\.url, authReasonOf\(error\?\.response\?\.headers\)\)/)
|
||||
})
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { readSource } from './helpers.ts'
|
||||
import {
|
||||
disableBlockReason,
|
||||
disableConfirmMessage,
|
||||
disabledBadgeText,
|
||||
} from '../src/pages/account/user-disable-model.ts'
|
||||
import { toAdminUserItem } from '../src/api/users-model.ts'
|
||||
|
||||
// ---------- 纯函数:确认文案与不可停原因 ----------
|
||||
|
||||
test('test_user_disable_confirm_message_names_the_kickout_cost', () => {
|
||||
// 停用的确认框必须说出代价:对方会被强制退出到登录页——只写"确定停用"等于没说
|
||||
const message = disableConfirmMessage({ id: 20, username: '小魏', role: 'normal' }, true)
|
||||
assert.match(message, /小魏/)
|
||||
assert.match(message, /强制退出/)
|
||||
assert.match(message, /登录页/)
|
||||
})
|
||||
|
||||
test('test_user_enable_confirm_message_offers_recovery', () => {
|
||||
const message = disableConfirmMessage({ id: 20, username: '小魏', role: 'normal' }, false)
|
||||
assert.match(message, /解除停用/)
|
||||
assert.match(message, /重新登录/)
|
||||
})
|
||||
|
||||
test('test_user_disable_block_reason_self', () => {
|
||||
assert.equal(disableBlockReason({ id: 9, username: 'op', role: 'super_admin' }, 9), '不能停用自己的账号')
|
||||
assert.equal(disableBlockReason({ id: 9, username: 'op', role: 'super_admin' }, 10), undefined)
|
||||
assert.equal(disableBlockReason(null, 9), '用户信息缺失,无法操作')
|
||||
})
|
||||
|
||||
test('test_user_disable_badge_text', () => {
|
||||
assert.equal(disabledBadgeText({ disabledAt: '2026-10-09 12:00' }), '已停用')
|
||||
assert.equal(disabledBadgeText({ disabledAt: null }), '正常')
|
||||
assert.equal(disabledBadgeText({}), '正常')
|
||||
})
|
||||
|
||||
// ---------- 列表负载解析:disabled_at 进 AdminUser ----------
|
||||
|
||||
test('test_user_disable_at_parsed_from_list_payload', () => {
|
||||
const disabled = toAdminUserItem({
|
||||
id: 20,
|
||||
username: '小魏',
|
||||
role: 'normal',
|
||||
disabled_at: '2026-10-09 12:00',
|
||||
})
|
||||
assert.equal(disabled?.disabledAt, '2026-10-09 12:00')
|
||||
|
||||
const normal = toAdminUserItem({ id: 21, username: '小李', role: 'normal', disabled_at: null })
|
||||
assert.equal(normal?.disabledAt, undefined, '未停用不得显示成已停用')
|
||||
})
|
||||
|
||||
// ---------- 接线(源码尺子:.vue/.ts 组件无挂载测试) ----------
|
||||
|
||||
test('test_user_disable_api_puts_disabled_switch', () => {
|
||||
const source = readSource('src/api/users.ts')
|
||||
assert.match(source, /setUserDisabled/, '缺停用 API 入口')
|
||||
assert.match(source, /http\.put<unknown>\(`\/api\/admin\/user\/\$\{uid\}`, \{ disabled \}\)/, 'PUT 必须只带 disabled 开关')
|
||||
})
|
||||
|
||||
test('test_user_disable_page_wires_confirm_and_toggle', () => {
|
||||
const source = readSource('src/pages/account/UsersPage.vue')
|
||||
assert.match(source, /disableBlockReason/, '停用前没过身份闸')
|
||||
assert.match(source, /disableConfirmMessage/, '没挂确认文案')
|
||||
assert.match(source, /setUserDisabled\(row\.id, wantDisable\)/, '按钮没接到停用 API')
|
||||
assert.match(source, /'解除停用' : '停用'/, '按钮文案没按状态切换')
|
||||
assert.match(source, /width: 90px">状态</, '列表缺「状态」列')
|
||||
assert.match(source, /disabledBadgeText/, '状态列没接徽标文案')
|
||||
})
|
||||
|
||||
test('test_user_disable_interceptor_carries_auth_reason', () => {
|
||||
const source = readSource('src/api/http.ts')
|
||||
assert.match(source, /x-auth-reason/, '拦截器没读 X-Auth-Reason 头')
|
||||
assert.match(source, /authReasonOf\(response\.headers\)/, '成功分支没带成因')
|
||||
assert.match(source, /authReasonOf\(error\?\.response\?\.headers\)/, '失败分支没带成因')
|
||||
assert.match(source, /&auth=\$\{reason\}|&auth=' \+ reason|reason \? `&auth=/, '成因没有随 query 带给登录页')
|
||||
})
|
||||
|
||||
test('test_user_disable_login_page_names_both_causes', () => {
|
||||
const source = readSource('src/pages/login/LoginPage.vue')
|
||||
assert.match(source, /route\.query\.auth === 'disabled'/)
|
||||
assert.match(source, /已被管理员停用/)
|
||||
assert.match(source, /route\.query\.auth === 'deleted'/)
|
||||
assert.match(source, /已被删除/)
|
||||
})
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
package com.nanri.aiimage.common.exception;
|
||||
|
||||
/**
|
||||
* 账号已被删除(硬删后 selectById 落空)。会话闸专用;
|
||||
* {@code GlobalExceptionHandler} 据此打 X-Auth-Reason: deleted,前端点名删除成因。
|
||||
*/
|
||||
public class AccountDeletedException extends BusinessException {
|
||||
|
||||
public static final String REASON = "deleted";
|
||||
|
||||
public AccountDeletedException(int code, String message) {
|
||||
super(code, message);
|
||||
}
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
package com.nanri.aiimage.common.exception;
|
||||
|
||||
/**
|
||||
* 账号已被管理员停用。登录闸(403)与会话闸(401)共用;
|
||||
* 会话路径上 {@code GlobalExceptionHandler} 据此打 X-Auth-Reason: disabled,
|
||||
* 前端据此在登录页点名停用成因。业务码仍沿用 401——改成新码会打断
|
||||
* 两面前端与桌面端既有的一切「code==401 才收口」的判定。
|
||||
*/
|
||||
public class AccountDisabledException extends BusinessException {
|
||||
|
||||
public static final String REASON = "disabled";
|
||||
|
||||
public AccountDisabledException(int code, String message) {
|
||||
super(code, message);
|
||||
}
|
||||
}
|
||||
+12
-1
@@ -24,6 +24,9 @@ import java.io.IOException;
|
||||
@RestControllerAdvice
|
||||
public class GlobalExceptionHandler {
|
||||
|
||||
/** 会话失效成因标记头:disabled=账号已停用、deleted=账号已删除;其余 401 不打此头。 */
|
||||
public static final String AUTH_REASON_HEADER = "X-Auth-Reason";
|
||||
|
||||
private final TaskOwnerForwardService taskOwnerForwardService;
|
||||
|
||||
@ExceptionHandler(TaskOwnerMismatchException.class)
|
||||
@@ -72,7 +75,15 @@ public class GlobalExceptionHandler {
|
||||
}
|
||||
|
||||
@ExceptionHandler(BusinessException.class)
|
||||
public ApiResponse<Void> handleBusinessException(BusinessException ex, HttpServletRequest request) {
|
||||
public ApiResponse<Void> handleBusinessException(BusinessException ex, HttpServletRequest request,
|
||||
jakarta.servlet.http.HttpServletResponse response) {
|
||||
// 停用/删除的成因走响应头而非新业务码:code 必须保持 401,改成新码会同时打断
|
||||
// 两面前端拦截器与桌面端 app_client/main.py 里按 'code': 401 识别鉴权失败的判定
|
||||
if (ex instanceof AccountDisabledException) {
|
||||
response.setHeader(AUTH_REASON_HEADER, AccountDisabledException.REASON);
|
||||
} else if (ex instanceof AccountDeletedException) {
|
||||
response.setHeader(AUTH_REASON_HEADER, AccountDeletedException.REASON);
|
||||
}
|
||||
// 业务异常此前完全不记日志:2026-09-16 线上「保存权限/创建用户」双双失败时,
|
||||
// 服务端只留 RequestTraceFilter 的 200 一行,根因只能靠反推响应体字节数才定位到。
|
||||
// 401/4011(未登录、被顶下线)属于轮询类接口的常态噪声,降为 debug 以免淹没真实业务错。
|
||||
|
||||
+3
-1
@@ -1,5 +1,6 @@
|
||||
package com.nanri.aiimage.common.security;
|
||||
|
||||
import com.nanri.aiimage.common.exception.AccountDisabledException;
|
||||
import com.nanri.aiimage.common.exception.BusinessException;
|
||||
import com.nanri.aiimage.common.mapper.AdminUserMapper;
|
||||
import com.nanri.aiimage.common.mapper.ShopManageGroupMapper;
|
||||
@@ -87,7 +88,8 @@ public class AccountExpiryService {
|
||||
*/
|
||||
private static void assertNotDisabled(java.time.LocalDateTime disabledAt, int code) {
|
||||
if (disabledAt != null) {
|
||||
throw new BusinessException(code, "账号已停用,请联系管理员");
|
||||
// 子类型只为了让 GlobalExceptionHandler 打 X-Auth-Reason: disabled;码与文案不变
|
||||
throw new AccountDisabledException(code, "账号已停用,请联系管理员");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@ package com.nanri.aiimage.common.security;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.ArrayList;
|
||||
import com.nanri.aiimage.common.exception.AccountDeletedException;
|
||||
import com.nanri.aiimage.common.exception.BusinessException;
|
||||
import com.nanri.aiimage.common.security.JwtService;
|
||||
import com.nanri.aiimage.common.security.DeviceSessionPolicy;
|
||||
@@ -66,7 +67,7 @@ public class AdminAuthSupport {
|
||||
AdminUserEntity user = adminUserMapper.selectById(userId);
|
||||
if (user == null) {
|
||||
// 硬删账号会留下孤儿在跑行:认人必须排在容忍之前,否则已删账号被自己的孤儿行继续供着
|
||||
throw new BusinessException(401, "用户不存在");
|
||||
throw new AccountDeletedException(401, "用户不存在");
|
||||
}
|
||||
// 吊销先于单设备比对:那条路径第一行就是 if (exempt) return;(超管豁免),
|
||||
// 把吊销挂在它下面等于超管永不见吊销
|
||||
|
||||
+6
@@ -16,4 +16,10 @@ public class AdminUserUpdateRequest {
|
||||
* yyyy-MM-dd[ HH:mm[:ss]],允许过去时间(立即到期 = 手工停用)。
|
||||
*/
|
||||
private String expiresAt;
|
||||
/**
|
||||
* 停用开关(V155):null=不动;true=停用(写 disabled_at,该账号已发令牌立刻 401、
|
||||
* 无法重新登录);false=解除停用(清 disabled_at,原 expires_at 不受影响)。
|
||||
* 普通账号也可被停用——停用是安全动作,不走「到期只设管理员」那条角色限制。
|
||||
*/
|
||||
private Boolean disabled;
|
||||
}
|
||||
|
||||
+3
@@ -25,6 +25,9 @@ public class AdminUserItemVo {
|
||||
/** 到期时间(yyyy-MM-dd HH:mm);空串=永不过期,前端按此渲染。 */
|
||||
@JsonProperty("expires_at")
|
||||
private String expiresAt;
|
||||
/** 管理员停用时刻(V155,yyyy-MM-dd HH:mm);null=未停用。 */
|
||||
@JsonProperty("disabled_at")
|
||||
private String disabledAt;
|
||||
@JsonProperty("pinyin_abbr")
|
||||
private String pinyinAbbr;
|
||||
}
|
||||
|
||||
+16
-1
@@ -385,9 +385,15 @@ public class AdminUserService {
|
||||
&& (wantRole == null || wantRole.isEmpty())
|
||||
&& request.getColumnIds() == null
|
||||
&& request.getCompanyId() == null
|
||||
&& request.getExpiresAt() == null) {
|
||||
&& request.getExpiresAt() == null
|
||||
&& request.getDisabled() == null) {
|
||||
throw new BusinessException("请提供要修改的内容");
|
||||
}
|
||||
// 不许停自己:现有的角色闸(admin 只动自建普通账号 / 公司超管与超管目标互斥)已经
|
||||
// 把三种角色都挡住了,这里显式再钉一道——上面的结构变了时,这道不能跟着悄悄消失。
|
||||
if (request.getDisabled() != null && currentUser.getId().equals(uid)) {
|
||||
throw new BusinessException(400, "不能停用自己的账号");
|
||||
}
|
||||
|
||||
AdminUserEntity target = adminUserMapper.selectById(uid);
|
||||
if (target == null) {
|
||||
@@ -468,6 +474,13 @@ public class AdminUserService {
|
||||
request.getExpiresAt().trim().isEmpty() ? null : parseExpiresAt(request.getExpiresAt()));
|
||||
dirty = true;
|
||||
}
|
||||
if (request.getDisabled() != null) {
|
||||
// 停用/解除停用。停用是硬停点:该账号已发令牌在下一次请求就被 assertSessionAllowed
|
||||
// 拒成 401(排在在跑容忍之前),前端据此强制退出到登录页。
|
||||
update.set(AdminUserEntity::getDisabledAt,
|
||||
Boolean.TRUE.equals(request.getDisabled()) ? LocalDateTime.now() : null);
|
||||
dirty = true;
|
||||
}
|
||||
String roleBefore = DeviceSessionPolicy.resolveRole(target.getRole(), target.getIsAdmin(),
|
||||
target.getCreatedById());
|
||||
if (request.getExpiresAt() == null && mayCarryOwnExpiry(roleBefore) && !mayCarryOwnExpiry(roleAfter)
|
||||
@@ -627,6 +640,8 @@ public class AdminUserService {
|
||||
vo.setUpdatedAt(updatedAt == null ? "" : updatedAt.format(CREATED_AT_FORMATTER));
|
||||
// 到期时间:null(永不过期)与空字符串在列表里都要有明确渲染,前端按空串判"永不过期"
|
||||
vo.setExpiresAt(entity.getExpiresAt() == null ? "" : entity.getExpiresAt().format(CREATED_AT_FORMATTER));
|
||||
// 停用时刻(V155):null=未停用,前端按此渲染「已停用」徽标
|
||||
vo.setDisabledAt(entity.getDisabledAt() == null ? null : entity.getDisabledAt().format(CREATED_AT_FORMATTER));
|
||||
vo.setPinyinAbbr(PinyinAbbrUtil.abbr(entity.getUsername()));
|
||||
return vo;
|
||||
}
|
||||
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
package com.nanri.aiimage.common.exception;
|
||||
|
||||
import com.nanri.aiimage.common.service.TaskOwnerForwardService;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
import org.springframework.mock.web.MockHttpServletResponse;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.Mockito.mock;
|
||||
|
||||
/**
|
||||
* 停用/删除的成因只走 X-Auth-Reason 头:业务码必须保持 401——改成新码会同时打断
|
||||
* 两面前端拦截器与桌面端按 'code': 401 识别鉴权失败的既有判定。
|
||||
* 摘掉这个头,前端就只会说通用「登录已失效」,用户读不出是被停用了。
|
||||
*/
|
||||
class GlobalExceptionHandlerAuthReasonTest {
|
||||
|
||||
private final GlobalExceptionHandler handler =
|
||||
new GlobalExceptionHandler(mock(TaskOwnerForwardService.class));
|
||||
|
||||
private final HttpServletRequest request = new MockHttpServletRequest();
|
||||
|
||||
@Test
|
||||
void disabledAccountMarksTheReasonHeader() {
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
handler.handleBusinessException(new AccountDisabledException(401, "账号已停用,请联系管理员"),
|
||||
request, response);
|
||||
|
||||
assertThat(response.getHeader(GlobalExceptionHandler.AUTH_REASON_HEADER)).isEqualTo("disabled");
|
||||
}
|
||||
|
||||
@Test
|
||||
void deletedAccountMarksTheReasonHeader() {
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
handler.handleBusinessException(new AccountDeletedException(401, "用户不存在"), request, response);
|
||||
|
||||
assertThat(response.getHeader(GlobalExceptionHandler.AUTH_REASON_HEADER)).isEqualTo("deleted");
|
||||
}
|
||||
|
||||
@Test
|
||||
void ordinaryBusinessExceptionCarriesNoReasonHeader() {
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
handler.handleBusinessException(new BusinessException(401, "登录已过期,请重新登录"), request, response);
|
||||
|
||||
assertThat(response.getHeader(GlobalExceptionHandler.AUTH_REASON_HEADER)).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void subtypesKeepTheSessionBusinessCode401() {
|
||||
assertThat(new AccountDisabledException(401, "x").getCode()).isEqualTo(401);
|
||||
assertThat(new AccountDeletedException(401, "x").getCode()).isEqualTo(401);
|
||||
}
|
||||
}
|
||||
+9
@@ -1,5 +1,6 @@
|
||||
package com.nanri.aiimage.common.security;
|
||||
|
||||
import com.nanri.aiimage.common.exception.AccountDisabledException;
|
||||
import com.nanri.aiimage.common.exception.BusinessException;
|
||||
import com.nanri.aiimage.common.mapper.AdminUserMapper;
|
||||
import com.nanri.aiimage.common.mapper.ShopManageGroupMapper;
|
||||
@@ -68,6 +69,14 @@ class AccountDisabledGateTest {
|
||||
assertThat(e.getMessage()).isEqualTo(MSG);
|
||||
}
|
||||
|
||||
@Test
|
||||
void sessionGateThrowsTheSubtypeTheHandlerStamps() {
|
||||
// 只断 BusinessException 的话,退回普通 BusinessException 头就没了(前端读不出停用成因)而用例照样绿
|
||||
assertThat(catchThrowableOfType(
|
||||
() -> service().assertSessionAllowed(admin(LocalDateTime.now())), BusinessException.class))
|
||||
.isInstanceOf(AccountDisabledException.class);
|
||||
}
|
||||
|
||||
/** 登录链路走的是另一张实体(同表同列),漏加就是「退出重登即复活」。 */
|
||||
@Test
|
||||
void disabledAccountOnLoginEntityIsAlsoBlocked() {
|
||||
|
||||
+143
@@ -0,0 +1,143 @@
|
||||
package com.nanri.aiimage.modules.admin.service;
|
||||
|
||||
import com.baomidou.mybatisplus.core.MybatisConfiguration;
|
||||
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
|
||||
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
|
||||
import com.nanri.aiimage.common.exception.BusinessException;
|
||||
import com.nanri.aiimage.common.mapper.AdminUserMapper;
|
||||
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
|
||||
import com.nanri.aiimage.common.security.AdminAuthSupport;
|
||||
import com.nanri.aiimage.modules.admin.model.dto.AdminUserUpdateRequest;
|
||||
import com.nanri.aiimage.modules.admin.spi.UserSecretCleanupPort;
|
||||
import com.nanri.aiimage.modules.auth.util.WerkzeugPasswordEncoder;
|
||||
import com.nanri.aiimage.modules.company.service.CompanyService;
|
||||
import com.nanri.aiimage.modules.permission.service.PermissionMenuService;
|
||||
import org.apache.ibatis.builder.MapperBuilderAssistant;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatCode;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyList;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.isNull;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* 停用/解除停用(V155)走 updateUser 的 disabled 开关。
|
||||
*
|
||||
* <p>断言全部打在真正落库的 UPDATE 的 SET 子句上:只 verify(update 被调了一次)
|
||||
* 是把「发了 UPDATE」当成「改了 disabled_at」的假绿。</p>
|
||||
*/
|
||||
class AdminUserDisableTest {
|
||||
|
||||
private AdminUserMapper userMapper;
|
||||
private AdminAuthSupport authSupport;
|
||||
private AdminUserService service;
|
||||
|
||||
@BeforeEach
|
||||
@SuppressWarnings("unchecked")
|
||||
void setUp() {
|
||||
TableInfoHelper.initTableInfo(
|
||||
new MapperBuilderAssistant(new MybatisConfiguration(), ""), AdminUserEntity.class);
|
||||
userMapper = mock(AdminUserMapper.class);
|
||||
WerkzeugPasswordEncoder passwordEncoder = mock(WerkzeugPasswordEncoder.class);
|
||||
authSupport = mock(AdminAuthSupport.class);
|
||||
PermissionMenuService permissionService = mock(PermissionMenuService.class);
|
||||
service = new AdminUserService(userMapper, passwordEncoder, authSupport, permissionService,
|
||||
mock(UserSecretCleanupPort.class), mock(CompanyService.class));
|
||||
when(permissionService.hasAnyAdminMenu(any(), anyList())).thenReturn(true);
|
||||
when(passwordEncoder.hash(anyString())).thenReturn("hashed");
|
||||
}
|
||||
|
||||
private AdminUserEntity operator(String role, Long companyId) {
|
||||
AdminUserEntity user = new AdminUserEntity();
|
||||
user.setId("super_admin".equals(role) ? 1L : 10L);
|
||||
user.setUsername("op");
|
||||
user.setRole(role);
|
||||
user.setIsAdmin("normal".equals(role) ? 0 : 1);
|
||||
user.setCreatedById(1L);
|
||||
user.setCompanyId(companyId);
|
||||
when(authSupport.currentRole(user)).thenReturn(role);
|
||||
return user;
|
||||
}
|
||||
|
||||
private AdminUserEntity target(Long createdById) {
|
||||
AdminUserEntity user = new AdminUserEntity();
|
||||
user.setId(20L);
|
||||
user.setUsername("target-user");
|
||||
user.setRole("normal");
|
||||
user.setIsAdmin(0);
|
||||
user.setCreatedById(createdById);
|
||||
when(userMapper.selectById(20L)).thenReturn(user);
|
||||
return user;
|
||||
}
|
||||
|
||||
private AdminUserUpdateRequest disableOnly(Boolean disabled) {
|
||||
AdminUserUpdateRequest request = new AdminUserUpdateRequest();
|
||||
request.setDisabled(disabled);
|
||||
return request;
|
||||
}
|
||||
|
||||
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||
private String setClause() {
|
||||
ArgumentCaptor<LambdaUpdateWrapper> captor = ArgumentCaptor.forClass((Class) LambdaUpdateWrapper.class);
|
||||
verify(userMapper).update(isNull(), captor.capture());
|
||||
String set = captor.getValue().getSqlSet();
|
||||
return set == null ? "" : set;
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("停用:只带 disabled=true 的请求是合法编辑,SET 里真的有 disabled_at")
|
||||
void disablingAloneIsAValidEditAndWritesDisabledAt() {
|
||||
AdminUserEntity op = operator("super_admin", 5L);
|
||||
target(88L);
|
||||
|
||||
assertThatCode(() -> service.updateUser(op, 20L, disableOnly(true))).doesNotThrowAnyException();
|
||||
|
||||
assertThat(setClause()).contains("disabled_at");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("解除停用:清 disabled_at,且不许顺手动收费到期字段")
|
||||
void enablingClearsDisabledAtWithoutTouchingExpiry() {
|
||||
AdminUserEntity op = operator("super_admin", 5L);
|
||||
target(88L);
|
||||
|
||||
assertThatCode(() -> service.updateUser(op, 20L, disableOnly(false))).doesNotThrowAnyException();
|
||||
|
||||
assertThat(setClause()).contains("disabled_at");
|
||||
assertThat(setClause()).doesNotContain("expires_at");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("归属门原样生效:admin 能停自己创建的普通账号")
|
||||
void adminMayDisableOwnNormalAccount() {
|
||||
AdminUserEntity op = operator("admin", 5L);
|
||||
target(op.getId());
|
||||
|
||||
assertThatCode(() -> service.updateUser(op, 20L, disableOnly(true))).doesNotThrowAnyException();
|
||||
|
||||
assertThat(setClause()).contains("disabled_at");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("不能停自己:显式闸门挡住并点名,一条 UPDATE 都不发")
|
||||
void selfDisableIsRefused() {
|
||||
AdminUserEntity op = operator("super_admin", 5L);
|
||||
|
||||
assertThatThrownBy(() -> service.updateUser(op, 1L, disableOnly(true)))
|
||||
.isInstanceOfSatisfying(BusinessException.class, ex -> {
|
||||
assertThat(ex.getCode()).isEqualTo(400);
|
||||
assertThat(ex.getMessage()).contains("不能停用自己的账号");
|
||||
});
|
||||
verify(userMapper, never()).update(any(), any());
|
||||
}
|
||||
}
|
||||
@@ -52,6 +52,8 @@
|
||||
<h1 class="login-title">登录</h1>
|
||||
<p v-if="kickedNotice" class="kicked-msg">该账号已在其他设备登录,本设备已下线。如非本人操作,请及时修改密码。</p>
|
||||
<p v-if="expiredNotice" class="kicked-msg">登录状态已失效(登录凭证过期,或该账号已被管理员删除),请重新登录。</p>
|
||||
<p v-if="disabledNotice" class="kicked-msg">该账号已被管理员停用,本设备已退出登录。如有疑问请联系管理员恢复后重新登录。</p>
|
||||
<p v-if="deletedNotice" class="kicked-msg">该账号已被管理员删除,本设备已退出登录。</p>
|
||||
<p v-if="errorMessage" class="error-msg">{{ errorMessage }}</p>
|
||||
<form id="loginForm" @submit.prevent="submitLogin">
|
||||
<div class="form-group">
|
||||
@@ -112,7 +114,7 @@
|
||||
import { onMounted, ref, watch } from 'vue'
|
||||
import { useRouter } from 'vue-router'
|
||||
import { loginWithDevice } from '@/shared/api/user'
|
||||
import { KICK_NOTICE_KEY, SESSION_EXPIRED_NOTICE_KEY } from '@/shared/auth/kick-handler'
|
||||
import { ACCOUNT_DELETED_NOTICE_KEY, ACCOUNT_DISABLED_NOTICE_KEY, KICK_NOTICE_KEY, SESSION_EXPIRED_NOTICE_KEY } from '@/shared/auth/kick-handler'
|
||||
import { COMPANY_NAME_STORAGE_KEY, writeCompanyIdentity } from '@/shared/auth/company-identity'
|
||||
import { clearAccountExpiry, writeAccountExpiry } from '@/shared/auth/account-expiry'
|
||||
import { useVersionUpdate } from '@/shared/composables/useVersionUpdate'
|
||||
@@ -137,6 +139,8 @@ const loggingIn = ref(false)
|
||||
const errorMessage = ref('')
|
||||
const kickedNotice = ref(false)
|
||||
const expiredNotice = ref(false)
|
||||
const disabledNotice = ref(false)
|
||||
const deletedNotice = ref(false)
|
||||
const rememberPassword = ref(false)
|
||||
const autoLogin = ref(false)
|
||||
const updateOpen = ref(false)
|
||||
@@ -295,6 +299,16 @@ function isSessionExpiredNav(): boolean {
|
||||
return lsGet(SESSION_EXPIRED_NOTICE_KEY) === '1'
|
||||
}
|
||||
|
||||
/** 账号被管理员停用后跳回登录页:标记由 kick-handler 按后端 X-Auth-Reason 写入 */
|
||||
function isAccountDisabledNav(): boolean {
|
||||
return lsGet(ACCOUNT_DISABLED_NOTICE_KEY) === '1'
|
||||
}
|
||||
|
||||
/** 账号被删除后跳回登录页:同上,与停用/过期分开存 */
|
||||
function isAccountDeletedNav(): boolean {
|
||||
return lsGet(ACCOUNT_DELETED_NOTICE_KEY) === '1'
|
||||
}
|
||||
|
||||
function togglePassword() {
|
||||
passwordVisible.value = !passwordVisible.value
|
||||
}
|
||||
@@ -510,12 +524,27 @@ onMounted(() => {
|
||||
lsRemove(SESSION_EXPIRED_NOTICE_KEY)
|
||||
}
|
||||
|
||||
if (isAccountDisabledNav()) {
|
||||
// 账号已被管理员停用:同样关自动登录,标记展示后即清。
|
||||
disabledNotice.value = true
|
||||
autoLogin.value = false
|
||||
lsSet(AUTO_LOGIN_KEY, '0')
|
||||
lsRemove(ACCOUNT_DISABLED_NOTICE_KEY)
|
||||
}
|
||||
|
||||
if (isAccountDeletedNav()) {
|
||||
deletedNotice.value = true
|
||||
autoLogin.value = false
|
||||
lsSet(AUTO_LOGIN_KEY, '0')
|
||||
lsRemove(ACCOUNT_DELETED_NOTICE_KEY)
|
||||
}
|
||||
|
||||
// 恢复记住的凭据并尝试自动登录(桌面与网页形态一致;登出/切号导航由 tryAutoLogin 内部豁免)
|
||||
// loadCredentials 现为异步(AES 解密),须先恢复密码再触发自动登录
|
||||
void (async () => {
|
||||
await loadCredentials()
|
||||
if (kickedNotice.value || expiredNotice.value) {
|
||||
// 刚被顶下线或登录态失效:不自动重登,等用户手动点登录(此时顶掉对方,最后登录者胜)
|
||||
if (kickedNotice.value || expiredNotice.value || disabledNotice.value || deletedNotice.value) {
|
||||
// 刚被顶下线/登录态失效/停用/删除:不自动重登,等用户手动点登录(此时顶掉对方,最后登录者胜)
|
||||
autoLogin.value = false
|
||||
return
|
||||
}
|
||||
|
||||
@@ -5,7 +5,7 @@ import axios, {
|
||||
type AxiosResponse,
|
||||
type InternalAxiosRequestConfig,
|
||||
} from 'axios'
|
||||
import { handleKicked, handleSessionExpired, isKickedPayload, isUnauthorizedPayload } from '../auth/kick-handler.ts'
|
||||
import { authReasonOf, handleKicked, handleSessionExpired, isKickedPayload, isUnauthorizedPayload } from '../auth/kick-handler.ts'
|
||||
|
||||
export interface LegacyApiSuccess<T> {
|
||||
success: true
|
||||
@@ -61,12 +61,17 @@ function responseStatusOf(error: unknown): unknown {
|
||||
return (error as { response?: { status?: unknown } } | null | undefined)?.response?.status
|
||||
}
|
||||
|
||||
/** 从 axios 错误对象里取响应头(兼容真实 AxiosError 与测试桩)。 */
|
||||
function responseHeadersOf(error: unknown): unknown {
|
||||
return (error as { response?: { headers?: unknown } } | null | undefined)?.response?.headers
|
||||
}
|
||||
|
||||
/** 响应成功分支:Java 业务错误是 HTTP 200 + body.code,下线收口必须在这里也判。 */
|
||||
export function onResponseFulfilled(response: AxiosResponse): AxiosResponse {
|
||||
if (isKickedPayload(response.data)) {
|
||||
handleKicked()
|
||||
} else if (isUnauthorizedPayload(response.data)) {
|
||||
handleSessionExpired()
|
||||
handleSessionExpired(authReasonOf(response.headers))
|
||||
}
|
||||
return response
|
||||
}
|
||||
@@ -77,7 +82,7 @@ export function onResponseRejected(error: unknown): Promise<never> {
|
||||
if (isKickedPayload(payload)) {
|
||||
handleKicked()
|
||||
} else if (isUnauthorizedPayload(payload) || responseStatusOf(error) === 401) {
|
||||
handleSessionExpired()
|
||||
handleSessionExpired(authReasonOf(responseHeadersOf(error)))
|
||||
}
|
||||
return Promise.reject(new Error(extractErrorMessage(error)))
|
||||
}
|
||||
|
||||
@@ -28,6 +28,21 @@ export const UNAUTHORIZED_CODE = 401
|
||||
/** 登录页据此标记显示"登录已失效"。与互踢分开存:两种成因不能互相冒充。 */
|
||||
export const SESSION_EXPIRED_NOTICE_KEY = 'aiimage_session_expired_notice'
|
||||
|
||||
/** 登录页据此标记显示"账号已被停用"。与其它成因分开存:四种成因不能互相冒充。 */
|
||||
export const ACCOUNT_DISABLED_NOTICE_KEY = 'aiimage_account_disabled_notice'
|
||||
|
||||
/** 登录页据此标记显示"账号已被删除"。 */
|
||||
export const ACCOUNT_DELETED_NOTICE_KEY = 'aiimage_account_deleted_notice'
|
||||
|
||||
/** 后端 X-Auth-Reason 头携带的会话失效成因;空串=未点名(令牌过期等)。 */
|
||||
export type AuthReason = 'disabled' | 'deleted' | ''
|
||||
|
||||
/** 从 axios 响应头里读会话失效成因(axios 归一化为全小写键名)。 */
|
||||
export function authReasonOf(headers: unknown): AuthReason {
|
||||
const value = (headers as Record<string, unknown> | null | undefined)?.['x-auth-reason']
|
||||
return value === 'disabled' || value === 'deleted' ? value : ''
|
||||
}
|
||||
|
||||
/** 本次页面生命周期内是否已发起跳转(并发 4011 只跳一次;整页跳转后 window 重建自然重置)。 */
|
||||
type KickWindow = Window & { __aiimageKickRedirected?: boolean }
|
||||
|
||||
@@ -96,12 +111,14 @@ function clearLocalSession(): void {
|
||||
}
|
||||
}
|
||||
|
||||
/** 亮出这一种成因的标记,同时清掉另一种:两个标记都在时登录页会说出错的那句。 */
|
||||
function setAuthNotice(key: string, otherKey: string): void {
|
||||
/** 亮出这一种成因的标记,同时清掉其它三种:多个标记都在时登录页会说出错的那句。 */
|
||||
function setAuthNotice(key: string, otherKeys: readonly string[]): void {
|
||||
try {
|
||||
const storage = window.localStorage
|
||||
storage.setItem(key, '1')
|
||||
storage.removeItem(otherKey)
|
||||
for (const other of otherKeys) {
|
||||
storage.removeItem(other)
|
||||
}
|
||||
} catch {
|
||||
/* 忽略存储异常 */
|
||||
}
|
||||
@@ -127,7 +144,7 @@ export function handleKicked(): void {
|
||||
return
|
||||
}
|
||||
clearLocalSession()
|
||||
setAuthNotice(KICK_NOTICE_KEY, SESSION_EXPIRED_NOTICE_KEY)
|
||||
setAuthNotice(KICK_NOTICE_KEY, [SESSION_EXPIRED_NOTICE_KEY, ACCOUNT_DISABLED_NOTICE_KEY, ACCOUNT_DELETED_NOTICE_KEY])
|
||||
clearDesktopCurrentUid()
|
||||
redirectToLogin('/login?kicked=1', '[auth] 账号已在其他设备登录,本设备下线,跳转登录页')
|
||||
}
|
||||
@@ -141,7 +158,7 @@ export function handleKicked(): void {
|
||||
* 只在"本端自认为已登录"时收口:匿名请求拿 401 是常态噪声(未登录打开首页、登录前的
|
||||
* 引导接口),为它清存储并整页跳转,会把一次无害的 401 变成"页面自己弹回登录页"。
|
||||
*/
|
||||
export function handleSessionExpired(): void {
|
||||
export function handleSessionExpired(reason: AuthReason = ''): void {
|
||||
if (typeof window === 'undefined') {
|
||||
return
|
||||
}
|
||||
@@ -149,7 +166,15 @@ export function handleSessionExpired(): void {
|
||||
return
|
||||
}
|
||||
clearLocalSession()
|
||||
setAuthNotice(SESSION_EXPIRED_NOTICE_KEY, KICK_NOTICE_KEY)
|
||||
// 成因点名:后端 X-Auth-Reason 说停用/删除就亮对应的标记,登录页照它说话;
|
||||
// 没带成因(旧 jar 部署窗口、非本成因的 401)回落到通用「登录已失效」。
|
||||
if (reason === 'disabled') {
|
||||
setAuthNotice(ACCOUNT_DISABLED_NOTICE_KEY, [KICK_NOTICE_KEY, SESSION_EXPIRED_NOTICE_KEY, ACCOUNT_DELETED_NOTICE_KEY])
|
||||
} else if (reason === 'deleted') {
|
||||
setAuthNotice(ACCOUNT_DELETED_NOTICE_KEY, [KICK_NOTICE_KEY, SESSION_EXPIRED_NOTICE_KEY, ACCOUNT_DISABLED_NOTICE_KEY])
|
||||
} else {
|
||||
setAuthNotice(SESSION_EXPIRED_NOTICE_KEY, [KICK_NOTICE_KEY, ACCOUNT_DISABLED_NOTICE_KEY, ACCOUNT_DELETED_NOTICE_KEY])
|
||||
}
|
||||
clearDesktopCurrentUid()
|
||||
redirectToLogin('/login?expired=1', '[auth] 登录态已失效,本设备下线,跳转登录页')
|
||||
}
|
||||
|
||||
@@ -0,0 +1,154 @@
|
||||
import { test } from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { resolve, dirname } from 'node:path'
|
||||
import { onResponseFulfilled, onResponseRejected } from '../src/shared/api/http.ts'
|
||||
import {
|
||||
ACCOUNT_DELETED_NOTICE_KEY,
|
||||
ACCOUNT_DISABLED_NOTICE_KEY,
|
||||
KICK_NOTICE_KEY,
|
||||
SESSION_EXPIRED_NOTICE_KEY,
|
||||
UNAUTHORIZED_CODE,
|
||||
authReasonOf,
|
||||
} from '../src/shared/auth/kick-handler.ts'
|
||||
|
||||
const here = dirname(fileURLToPath(import.meta.url))
|
||||
|
||||
/** 登录页是 .vue 组件,本树无挂载测试(无 @vue/test-utils),按既有惯例用源码尺子钉。 */
|
||||
const loginPageSource = readFileSync(
|
||||
resolve(here, '../src/pages/login/DesktopLoginPage.vue'),
|
||||
'utf-8',
|
||||
)
|
||||
|
||||
function createStorage(initial: Record<string, string> = {}) {
|
||||
const store = new Map(Object.entries(initial))
|
||||
return {
|
||||
getItem: (key: string) => (store.has(key) ? (store.get(key) as string) : null),
|
||||
setItem: (key: string, value: string) => void store.set(key, String(value)),
|
||||
removeItem: (key: string) => void store.delete(key),
|
||||
}
|
||||
}
|
||||
|
||||
function setupWindow(initial: Record<string, string> = {}, pathname = '/home') {
|
||||
const localStorage = createStorage(initial)
|
||||
const assigned: string[] = []
|
||||
;(globalThis as Record<string, unknown>).window = {
|
||||
localStorage,
|
||||
location: {
|
||||
pathname,
|
||||
search: '',
|
||||
assign: (url: string) => {
|
||||
assigned.push(url)
|
||||
},
|
||||
},
|
||||
addEventListener: () => undefined,
|
||||
}
|
||||
return { localStorage, assigned }
|
||||
}
|
||||
|
||||
function loggedInStorage() {
|
||||
return {
|
||||
aiimage_auth_token: 'jwt-token',
|
||||
uid: '1206',
|
||||
username: '先锋',
|
||||
aiimage_auto_login: '1',
|
||||
}
|
||||
}
|
||||
|
||||
/** 后端把「停用/删除/过期」都编译成 HTTP 200 + body.code=401;成因在 X-Auth-Reason 头上。 */
|
||||
function unauthorizedEnvelope(message = '账号已停用,请联系管理员') {
|
||||
return { success: false, code: UNAUTHORIZED_CODE, message }
|
||||
}
|
||||
|
||||
test('authReasonOf 只认 disabled/deleted,其余回落空串', () => {
|
||||
assert.equal(authReasonOf({ 'x-auth-reason': 'disabled' }), 'disabled')
|
||||
assert.equal(authReasonOf({ 'x-auth-reason': 'deleted' }), 'deleted')
|
||||
assert.equal(authReasonOf({ 'x-auth-reason': 'expired' }), '')
|
||||
assert.equal(authReasonOf({}), '')
|
||||
assert.equal(authReasonOf(undefined), '')
|
||||
})
|
||||
|
||||
test('停用必须强制下线且点名停用:清登录态、亮停用标记、清掉其它成因', () => {
|
||||
const { localStorage, assigned } = setupWindow({
|
||||
...loggedInStorage(),
|
||||
[KICK_NOTICE_KEY]: '1',
|
||||
})
|
||||
|
||||
onResponseFulfilled({ data: unauthorizedEnvelope(), headers: { 'x-auth-reason': 'disabled' } })
|
||||
|
||||
assert.equal(localStorage.getItem('aiimage_auth_token'), null, '停用不清令牌=用户停在原页面')
|
||||
assert.equal(localStorage.getItem('aiimage_auto_login'), '0', '不关自动登录=被停用账号每次启动静默重试')
|
||||
assert.equal(localStorage.getItem(ACCOUNT_DISABLED_NOTICE_KEY), '1')
|
||||
assert.equal(localStorage.getItem(KICK_NOTICE_KEY), null, '停用不能说成被顶下线')
|
||||
assert.deepEqual(assigned, ['/login?expired=1'])
|
||||
})
|
||||
|
||||
test('删除点名:亮删除标记并清掉停用/互踢标记', () => {
|
||||
const { localStorage } = setupWindow({
|
||||
...loggedInStorage(),
|
||||
[ACCOUNT_DISABLED_NOTICE_KEY]: '1',
|
||||
})
|
||||
|
||||
onResponseFulfilled({ data: unauthorizedEnvelope('用户不存在'), headers: { 'x-auth-reason': 'deleted' } })
|
||||
|
||||
assert.equal(localStorage.getItem(ACCOUNT_DELETED_NOTICE_KEY), '1')
|
||||
assert.equal(localStorage.getItem(ACCOUNT_DISABLED_NOTICE_KEY), null, '删除不能说成停用')
|
||||
assert.equal(localStorage.getItem(KICK_NOTICE_KEY), null)
|
||||
})
|
||||
|
||||
test('401 头里没有成因:回落通用「登录已失效」,不得误亮停用/删除标记', () => {
|
||||
const { localStorage } = setupWindow(loggedInStorage())
|
||||
|
||||
onResponseFulfilled({ data: unauthorizedEnvelope('登录已过期,请重新登录') })
|
||||
|
||||
assert.equal(localStorage.getItem(SESSION_EXPIRED_NOTICE_KEY), '1')
|
||||
assert.equal(localStorage.getItem(ACCOUNT_DISABLED_NOTICE_KEY), null)
|
||||
assert.equal(localStorage.getItem(ACCOUNT_DELETED_NOTICE_KEY), null)
|
||||
})
|
||||
|
||||
test('成因只改标记不改收口动作:带头 401 照样跳 /login?expired=1', async () => {
|
||||
const { assigned } = setupWindow(loggedInStorage())
|
||||
|
||||
await assert.rejects(
|
||||
() => onResponseRejected({
|
||||
response: { status: 401, data: { message: '' }, headers: { 'x-auth-reason': 'disabled' } },
|
||||
message: '请求失败',
|
||||
}),
|
||||
/请求失败/,
|
||||
)
|
||||
|
||||
assert.deepEqual(assigned, ['/login?expired=1'])
|
||||
})
|
||||
|
||||
// ---------- 登录页接线(.vue 无挂载测试,源码尺子钉) ----------
|
||||
|
||||
test('登录页认停用/删除标记:各有判定入口、各自关自动登录', () => {
|
||||
assert.match(loginPageSource, /function isAccountDisabledNav\(\): boolean/, '缺停用判定入口')
|
||||
assert.match(loginPageSource, /function isAccountDeletedNav\(\): boolean/, '缺删除判定入口')
|
||||
assert.match(loginPageSource, /lsGet\(ACCOUNT_DISABLED_NOTICE_KEY\)/)
|
||||
assert.match(loginPageSource, /lsGet\(ACCOUNT_DELETED_NOTICE_KEY\)/)
|
||||
assert.match(loginPageSource, /disabledNotice\.value = true/, '判定到了却没显示停用提示')
|
||||
assert.match(loginPageSource, /deletedNotice\.value = true/, '判定到了却没显示删除提示')
|
||||
// 自动登录豁免必须包含全部四种成因:漏一种,那种账号每次启动就静默重登
|
||||
assert.match(
|
||||
loginPageSource,
|
||||
/kickedNotice\.value \|\| expiredNotice\.value \|\| disabledNotice\.value \|\| deletedNotice\.value/,
|
||||
'自动登录豁免漏了停用/删除成因',
|
||||
)
|
||||
})
|
||||
|
||||
test('停用/删除文案必须互不冒充:停用句不说删除、删除句不说停用', () => {
|
||||
const disabledLine = loginPageSource
|
||||
.split('\n')
|
||||
.find((line) => line.includes('v-if="disabledNotice"')) || ''
|
||||
const deletedLine = loginPageSource
|
||||
.split('\n')
|
||||
.find((line) => line.includes('v-if="deletedNotice"')) || ''
|
||||
assert.ok(disabledLine, '模板里没有 disabledNotice 那一行')
|
||||
assert.ok(deletedLine, '模板里没有 deletedNotice 那一行')
|
||||
assert.match(disabledLine, /停用/)
|
||||
assert.ok(!disabledLine.includes('删除'), '停用提示不能说成被删除')
|
||||
assert.match(deletedLine, /删除/)
|
||||
assert.ok(!deletedLine.includes('停用'), '删除提示不能说成被停用')
|
||||
})
|
||||
Reference in New Issue
Block a user