feat(认证/通知): 单设备登录互踢 + 站内通知铃铛系统

- 单设备登录:登录成功即 last-login-wins 绑定 users.machine;非超管旧 token
  在下一次受保护请求抛 4011 下线,超管豁免;仅认 token 内签名 deviceId,不用请求头。
  前端两端接入踢下线跳转(?kicked=1 提示),V118 清空历史 machine
- 站内通知:新增 notification 模块(任务失败扫描 / 密钥欠费 / 下游服务探测三类来源),
  前后台铃铛组件 + 轮询;后台列表按主管数据范围(UserDataScopeSupport)过滤;V116 建表

均已于 2026-09-13 部署上线,此次补提交源码(此前仅存在于已部署 JAR/构建产物中)
This commit is contained in:
2026-09-13 23:08:22 +08:00
parent 41674d1adb
commit 43b1a0a955
53 changed files with 3982 additions and 101 deletions
@@ -0,0 +1,184 @@
package com.nanri.aiimage.modules.auth.service;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.modules.auth.config.AuthProperties;
import com.nanri.aiimage.modules.auth.mapper.LoginUserMapper;
import com.nanri.aiimage.modules.auth.model.dto.LoginRequest;
import com.nanri.aiimage.modules.auth.model.entity.LoginUserEntity;
import com.nanri.aiimage.modules.auth.model.vo.LoginResultVo;
import com.nanri.aiimage.modules.auth.util.WerkzeugPasswordEncoder;
import com.nanri.aiimage.modules.permission.service.PermissionMenuService;
import io.jsonwebtoken.Claims;
import org.apache.ibatis.builder.MapperBuilderAssistant;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.assertj.core.api.Assertions.catchThrowableOfType;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class AuthServiceTest {
@BeforeEach
void setUp() {
// lambda 列名解析需要 MyBatis-Plus TableInfo 缓存;mock 环境手动初始化。
TableInfoHelper.initTableInfo(new MapperBuilderAssistant(new MybatisConfiguration(), ""),
LoginUserEntity.class);
}
// ---------- login:绑定当前设备 ----------
@Test
void loginBindsAccountToCurrentDevice() {
Fixture f = fixture(true);
when(f.loginUserMapper.selectOne(any())).thenReturn(f.user("devA"));
when(f.passwordEncoder.matches("pwd", "hash")).thenReturn(true);
when(f.jwtService.issue(eq(7L), anyString(), anyString())).thenReturn("jwt-token");
LoginRequest request = new LoginRequest();
request.setUsername("u7");
request.setPassword("pwd");
request.setDeviceId("devB");
LoginResultVo vo = f.service.login(request);
// 绑定写入当前设备(last-login-wins),签发的 token 也用当前设备
verify(f.loginUserMapper, times(1)).update(any(), any());
verify(f.jwtService).issue(7L, "u7", "devB");
assertThat(vo.getDeviceId()).isEqualTo("devB");
}
@Test
void loginSkipsBindingWhenSingleDeviceDisabled() {
Fixture f = fixture(false);
when(f.loginUserMapper.selectOne(any())).thenReturn(f.user("devA"));
when(f.passwordEncoder.matches("pwd", "hash")).thenReturn(true);
when(f.jwtService.issue(eq(7L), anyString(), anyString())).thenReturn("jwt-token");
LoginRequest request = new LoginRequest();
request.setUsername("u7");
request.setPassword("pwd");
request.setDeviceId("devB");
f.service.login(request);
verify(f.loginUserMapper, never()).update(any(), any());
}
// ---------- check_login:被顶下线必须拦截且不续期 ----------
@Test
void checkLoginRejectsSupersededDeviceWithoutRenewal() {
Fixture f = fixture(true);
Claims claims = f.claims("devB");
when(f.jwtService.parse("t")).thenReturn(claims);
when(f.loginUserMapper.selectById(7L)).thenReturn(f.user("devA"));
BusinessException ex = catchThrowableOfType(() -> f.service.checkLogin("t", null), BusinessException.class);
assertThat(ex.getCode()).isEqualTo(4011);
assertThat(ex.getMessage()).contains("已在其他设备登录");
// 关键:被踢的旧 token 不能在这里换到新 token「复活」
verify(f.jwtService, never()).issue(any(), anyString(), anyString());
}
@Test
void checkLoginPassesAndRenewsWithClaimDevice() {
Fixture f = fixture(true);
Claims claims = f.claims("devA");
when(f.jwtService.parse("t")).thenReturn(claims);
when(f.loginUserMapper.selectById(7L)).thenReturn(f.user("devA"));
when(f.jwtService.issue(eq(7L), anyString(), anyString())).thenReturn("jwt-token");
LoginResultVo vo = f.service.checkLogin("t", null);
verify(f.jwtService).issue(7L, "u7", "devA");
assertThat(vo.getDeviceId()).isEqualTo("devA");
}
@Test
void checkLoginIgnoresSpoofedHeaderDevice() {
// 校验以 token 内签名的 deviceId 为准:请求头塞别的设备号不影响判定,也不能签进新 token
Fixture f = fixture(true);
Claims claims = f.claims("devB");
when(f.jwtService.parse("t")).thenReturn(claims);
when(f.loginUserMapper.selectById(7L)).thenReturn(f.user("devA"));
BusinessException ex = catchThrowableOfType(
() -> f.service.checkLogin("t", "devA"), BusinessException.class);
assertThat(ex.getCode()).isEqualTo(4011);
}
@Test
void checkLoginExemptsSuperAdmin() {
Fixture f = fixture(true);
Claims claims = f.claims("devB");
when(f.jwtService.parse("t")).thenReturn(claims);
LoginUserEntity root = f.user("devA");
root.setRole("super_admin");
root.setIsAdmin(1);
when(f.loginUserMapper.selectById(7L)).thenReturn(root);
when(f.jwtService.issue(eq(7L), anyString(), anyString())).thenReturn("jwt-token");
assertThatCode(() -> f.service.checkLogin("t", null)).doesNotThrowAnyException();
}
@Test
void checkLoginPassesWhenSingleDeviceDisabled() {
Fixture f = fixture(false);
Claims claims = f.claims("devB");
when(f.jwtService.parse("t")).thenReturn(claims);
when(f.loginUserMapper.selectById(7L)).thenReturn(f.user("devA"));
when(f.jwtService.issue(eq(7L), anyString(), anyString())).thenReturn("jwt-token");
assertThatCode(() -> f.service.checkLogin("t", null)).doesNotThrowAnyException();
}
// ---------- 夹具 ----------
private Fixture fixture(boolean singleDeviceEnabled) {
LoginUserMapper loginUserMapper = mock(LoginUserMapper.class);
WerkzeugPasswordEncoder passwordEncoder = mock(WerkzeugPasswordEncoder.class);
JwtService jwtService = mock(JwtService.class);
PermissionMenuService permissionMenuService = mock(PermissionMenuService.class);
AuthProperties authProperties = mock(AuthProperties.class);
when(authProperties.isSingleDeviceEnabled()).thenReturn(singleDeviceEnabled);
when(jwtService.ttlSeconds()).thenReturn(604800L);
AuthService service = new AuthService(loginUserMapper, passwordEncoder, jwtService,
permissionMenuService, authProperties);
return new Fixture(service, loginUserMapper, passwordEncoder, jwtService);
}
private record Fixture(AuthService service, LoginUserMapper loginUserMapper,
WerkzeugPasswordEncoder passwordEncoder, JwtService jwtService) {
LoginUserEntity user(String machine) {
LoginUserEntity user = new LoginUserEntity();
user.setId(7L);
user.setUsername("u7");
user.setPasswordHash("hash");
user.setIsAdmin(0);
user.setRole("normal");
user.setMachine(machine);
return user;
}
Claims claims(String deviceId) {
Claims claims = mock(Claims.class);
when(claims.getSubject()).thenReturn("7");
when(claims.get("deviceId")).thenReturn(deviceId);
return claims;
}
}
}
@@ -0,0 +1,101 @@
package com.nanri.aiimage.modules.auth.support;
import com.nanri.aiimage.common.exception.BusinessException;
import io.jsonwebtoken.Claims;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.assertj.core.api.Assertions.catchThrowableOfType;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class DeviceSessionPolicyTest {
// ---------- 角色规则(从 AdminAuthSupport.currentRole 迁移,行为必须保持一致) ----------
@Test
void explicitSuperAdminResolved() {
assertThat(DeviceSessionPolicy.resolveRole("super_admin", 1, 9L)).isEqualTo("super_admin");
}
@Test
void explicitAdminNotPromotedToSuperAdmin() {
assertThat(DeviceSessionPolicy.resolveRole("admin", 1, null)).isEqualTo("admin");
}
@Test
void legacyBlankRoleRootRemainsSuperAdmin() {
assertThat(DeviceSessionPolicy.resolveRole(null, 1, null)).isEqualTo("super_admin");
}
@Test
void legacyBlankRoleCreatedByOtherIsAdmin() {
assertThat(DeviceSessionPolicy.resolveRole("", 1, 3L)).isEqualTo("admin");
}
@Test
void normalRoleIsNotPromotedByLegacyAdminFields() {
assertThat(DeviceSessionPolicy.resolveRole("normal", 1, null)).isNull();
}
@Test
void isSuperAdminOnlyForSuperAdmin() {
assertThat(DeviceSessionPolicy.isSuperAdmin("super_admin", 1, null)).isTrue();
assertThat(DeviceSessionPolicy.isSuperAdmin("admin", 1, null)).isFalse();
assertThat(DeviceSessionPolicy.isSuperAdmin("normal", 0, null)).isFalse();
}
// ---------- 设备一致性校验 ----------
@Test
void exemptUserAlwaysPasses() {
// 超管豁免:设备不一致也放行
assertThatCode(() -> DeviceSessionPolicy.assertSameDevice("devA", "devB", true, 7L, "root"))
.doesNotThrowAnyException();
}
@Test
void unboundMachinePasses() {
// 尚未绑定(machine 为空)放行,下次登录写入后开始生效
assertThatCode(() -> DeviceSessionPolicy.assertSameDevice(null, "devB", false, 7L, "u1"))
.doesNotThrowAnyException();
assertThatCode(() -> DeviceSessionPolicy.assertSameDevice(" ", "devB", false, 7L, "u1"))
.doesNotThrowAnyException();
}
@Test
void sameDevicePasses() {
assertThatCode(() -> DeviceSessionPolicy.assertSameDevice("devA", "devA", false, 7L, "u1"))
.doesNotThrowAnyException();
}
@Test
void differentDeviceThrowsKicked() {
BusinessException ex = catchThrowableOfType(
() -> DeviceSessionPolicy.assertSameDevice("devA", "devB", false, 7L, "u1"),
BusinessException.class);
assertThat(ex.getCode()).isEqualTo(DeviceSessionPolicy.CODE_KICKED);
assertThat(ex.getMessage()).contains("已在其他设备登录");
}
@Test
void blankClaimDeviceThrowsUnauthorized() {
// 正常 token 必带 deviceId claim;缺失按登录态无效处理(普通 401,不误报"被踢")
BusinessException ex = catchThrowableOfType(
() -> DeviceSessionPolicy.assertSameDevice("devA", null, false, 7L, "u1"),
BusinessException.class);
assertThat(ex.getCode()).isEqualTo(401);
}
@Test
void claimDeviceIdExtractsAndTrims() {
assertThat(DeviceSessionPolicy.claimDeviceId(null)).isEmpty();
Claims claims = mock(Claims.class);
when(claims.get("deviceId")).thenReturn(" devA ");
assertThat(DeviceSessionPolicy.claimDeviceId(claims)).isEqualTo("devA");
}
}