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:
+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());
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user