feat(admin): 增加账号管理与 Token 签发审计

This commit is contained in:
my_local_kimi_dev2
2026-11-18 11:57:33 +08:00
parent ba2ffabf19
commit 2a8c9260a6
14 changed files with 701 additions and 21 deletions
@@ -0,0 +1,54 @@
package me.iiv.agent.admin;
import jakarta.servlet.http.HttpSession;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@RequestMapping("/api/admin/accounts")
public class AdminAccountController {
private final AdminAccountService service;
public AdminAccountController(AdminAccountService service) {
this.service = service;
}
@GetMapping
public List<AdminAccountService.AccountView> list() {
return service.list();
}
@PostMapping
public AdminAccountService.AccountView create(@RequestBody AdminAccountService.AccountRequest body,
HttpSession session) {
return service.create(body, adminId(session));
}
@PutMapping("/{id}")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void update(@PathVariable Long id, @RequestBody AdminAccountService.AccountRequest body,
HttpSession session) {
service.update(id, body, adminId(session));
}
@DeleteMapping("/{id}")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void delete(@PathVariable Long id, HttpSession session) {
service.delete(id, adminId(session));
}
private static Long adminId(HttpSession session) {
return (Long) session.getAttribute(AdminSessionFilter.ADMIN_SESSION_ID);
}
}
@@ -0,0 +1,130 @@
package me.iiv.agent.admin;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import me.iiv.agent.entity.svc.AdminUser;
import me.iiv.agent.mapper.svc.AdminUserMapper;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.server.ResponseStatusException;
import java.util.Date;
import java.util.List;
@Service
public class AdminAccountService {
private final AdminUserMapper mapper;
private final AdminPasswordHasher hasher;
public AdminAccountService(AdminUserMapper mapper, AdminPasswordHasher hasher) {
this.mapper = mapper;
this.hasher = hasher;
}
public List<AccountView> list() {
return mapper.selectList(new LambdaQueryWrapper<AdminUser>()
.eq(AdminUser::getSoftDelete, 0).orderByDesc(AdminUser::getId))
.stream().map(AdminAccountService::view).toList();
}
@Transactional(transactionManager = "svcTransactionManager")
public AccountView create(AccountRequest body, Long operatorId) {
String account = validate(body, null, true);
AdminUser admin = new AdminUser();
admin.setAccount(account);
admin.setPasswordHash(hasher.hash(body.password()));
admin.setName(normalizeName(body.name()));
admin.setStatus(body.status() == null ? (byte) 1 : body.status());
admin.setCreateId(operatorId);
admin.setModifyId(operatorId);
admin.setSoftDelete((byte) 0);
mapper.insert(admin);
return view(admin);
}
@Transactional(transactionManager = "svcTransactionManager")
public void update(Long id, AccountRequest body, Long operatorId) {
AdminUser admin = active(id);
String account = validate(body, id, false);
if ("admin".equals(admin.getAccount()) && !"admin".equals(account)) {
conflict("内置 admin 账号不能改名");
}
byte status = body.status() == null ? admin.getStatus() : body.status();
if (id.equals(operatorId) && status == 0) conflict("不能禁用当前登录账号");
if (Byte.valueOf((byte) 1).equals(admin.getStatus()) && status == 0) ensureAnotherActive(id);
admin.setAccount(account);
admin.setName(normalizeName(body.name()));
admin.setStatus(status);
if (body.password() != null && !body.password().isBlank()) {
admin.setPasswordHash(hasher.hash(body.password()));
}
admin.setModifyId(operatorId);
mapper.updateById(admin);
}
@Transactional(transactionManager = "svcTransactionManager")
public void delete(Long id, Long operatorId) {
AdminUser admin = active(id);
if (id.equals(operatorId)) conflict("不能删除当前登录账号");
if (Byte.valueOf((byte) 1).equals(admin.getStatus())) ensureAnotherActive(id);
admin.setStatus((byte) 0);
admin.setSoftDelete((byte) 1);
admin.setModifyId(operatorId);
mapper.updateById(admin);
}
private String validate(AccountRequest body, Long currentId, boolean creating) {
if (body == null) bad("请求内容不能为空");
if (body.account() == null || body.account().isBlank() || body.account().length() > 64) {
bad("登录账号不能为空且最多 64 字");
}
if (body.name() != null && body.name().length() > 64) bad("姓名最多 64 字");
if (body.status() != null && body.status() != 0 && body.status() != 1) bad("账号状态无效");
if (creating || (body.password() != null && !body.password().isBlank())) {
if (body.password() == null || body.password().length() < 12 || body.password().length() > 1024) {
bad("密码长度须为 12 至 1024 位");
}
}
String account = body.account().trim();
AdminUser duplicate = mapper.selectOne(new LambdaQueryWrapper<AdminUser>()
.eq(AdminUser::getAccount, account)
.ne(currentId != null, AdminUser::getId, currentId));
if (duplicate != null) conflict("登录账号已存在");
return account;
}
private void ensureAnotherActive(Long excludedId) {
Long count = mapper.selectCount(new LambdaQueryWrapper<AdminUser>()
.eq(AdminUser::getStatus, 1).eq(AdminUser::getSoftDelete, 0)
.ne(AdminUser::getId, excludedId));
if (count == null || count == 0) conflict("至少保留一个正常状态的管理后台账号");
}
private AdminUser active(Long id) {
AdminUser admin = mapper.selectById(id);
if (admin == null || !Byte.valueOf((byte) 0).equals(admin.getSoftDelete())) bad("账号不存在");
return admin;
}
private static AccountView view(AdminUser admin) {
return new AccountView(admin.getId(), admin.getAccount(), admin.getName(), admin.getStatus(),
admin.getCreateTime(), admin.getModifyTime());
}
private static String normalizeName(String name) {
return name == null || name.isBlank() ? null : name.trim();
}
private static void bad(String message) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, message);
}
private static void conflict(String message) {
throw new ResponseStatusException(HttpStatus.CONFLICT, message);
}
public record AccountRequest(String account, String password, String name, Byte status) {}
public record AccountView(Long id, String account, String name, Byte status,
Date createTime, Date modifyTime) {}
}
@@ -56,7 +56,7 @@ public class AdminAuthController {
if (admin == null || admin.getStatus() == null || admin.getStatus() != 1
|| admin.getSoftDelete() == null || admin.getSoftDelete() != 0) throw unauthorized();
return new SessionView(id, admin.getAccount(),
(String) session.getAttribute(AdminSessionFilter.ADMIN_SESSION_NAME),
admin.getName() == null ? admin.getAccount() : admin.getName(),
(String) session.getAttribute(AdminSessionFilter.CSRF_SESSION_KEY));
}
@@ -5,6 +5,8 @@ import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import me.iiv.agent.entity.svc.AdminUser;
import me.iiv.agent.mapper.svc.AdminUserMapper;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
@@ -18,6 +20,12 @@ public class AdminSessionFilter extends OncePerRequestFilter {
static final String ADMIN_SESSION_NAME = "adminName";
static final String CSRF_SESSION_KEY = "adminCsrf";
private final AdminUserMapper adminUserMapper;
public AdminSessionFilter(AdminUserMapper adminUserMapper) {
this.adminUserMapper = adminUserMapper;
}
@Override
protected boolean shouldNotFilter(HttpServletRequest request) {
return !request.getRequestURI().startsWith("/api/admin/");
@@ -37,6 +45,21 @@ public class AdminSessionFilter extends OncePerRequestFilter {
error(response, 401, "请先登录");
return;
}
Long adminId = (Long) session.getAttribute(ADMIN_SESSION_ID);
AdminUser admin = adminUserMapper.selectById(adminId);
if (admin == null || !Byte.valueOf((byte) 1).equals(admin.getStatus())
|| !Byte.valueOf((byte) 0).equals(admin.getSoftDelete())) {
session.invalidate();
error(response, 401, "账号已禁用或删除,请重新登录");
return;
}
if (("/api/admin/accounts".equals(uri) || uri.startsWith("/api/admin/accounts/"))
&& !"admin".equals(admin.getAccount())) {
error(response, 403, "仅 admin 可管理后台账号");
return;
}
session.setAttribute(ADMIN_SESSION_NAME,
admin.getName() == null ? admin.getAccount() : admin.getName());
Object csrf = session.getAttribute(CSRF_SESSION_KEY);
if (isMutation(request.getMethod())
&& (csrf == null || !csrf.equals(request.getHeader("X-CSRF-Token")))) {
@@ -2,10 +2,12 @@ package me.iiv.agent.admin;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import me.iiv.agent.entity.m0.User;
import me.iiv.agent.entity.svc.AdminUser;
import me.iiv.agent.entity.svc.AgentApiKey;
import me.iiv.agent.entity.svc.AgentScope;
import me.iiv.agent.entity.svc.TokenScope;
import me.iiv.agent.mapper.m0.UserMapper;
import me.iiv.agent.mapper.svc.AdminUserMapper;
import me.iiv.agent.mapper.svc.AgentApiKeyMapper;
import me.iiv.agent.mapper.svc.AgentScopeMapper;
import me.iiv.agent.mapper.svc.TokenScopeMapper;
@@ -18,6 +20,9 @@ import org.springframework.web.server.ResponseStatusException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
@Service
public class AdminTokenService {
@@ -27,15 +32,17 @@ public class AdminTokenService {
private final TokenScopeMapper relationMapper;
private final AgentScopeMapper scopeMapper;
private final TokenCipher tokenCipher;
private final AdminUserMapper adminUserMapper;
public AdminTokenService(UserMapper userMapper, AgentApiKeyMapper tokenMapper,
TokenScopeMapper relationMapper, AgentScopeMapper scopeMapper,
TokenCipher tokenCipher) {
TokenCipher tokenCipher, AdminUserMapper adminUserMapper) {
this.userMapper = userMapper;
this.tokenMapper = tokenMapper;
this.relationMapper = relationMapper;
this.scopeMapper = scopeMapper;
this.tokenCipher = tokenCipher;
this.adminUserMapper = adminUserMapper;
}
/**
@@ -184,10 +191,21 @@ public class AdminTokenService {
List<AgentApiKey> tokens = tokenMapper.selectList(new LambdaQueryWrapper<AgentApiKey>()
.eq(AgentApiKey::getUserId, userId).eq(AgentApiKey::getSoftDelete, 0)
.orderByDesc(AgentApiKey::getCreateTime));
return tokens.stream().map(this::view).toList();
Set<Long> issuerIds = tokens.stream().map(AgentApiKey::getCreateId)
.filter(id -> id != null && id > 0).collect(Collectors.toSet());
Map<Long, AdminUser> issuers = issuerIds.isEmpty() ? Map.of()
: adminUserMapper.selectBatchIds(issuerIds).stream()
.collect(Collectors.toMap(AdminUser::getId, admin -> admin));
return tokens.stream().map(token -> view(token, issuers.get(token.getCreateId()))).toList();
}
private TokenView view(AgentApiKey token) {
AdminUser issuer = token.getCreateId() == null || token.getCreateId() <= 0
? null : adminUserMapper.selectById(token.getCreateId());
return view(token, issuer);
}
private TokenView view(AgentApiKey token, AdminUser issuer) {
List<Long> scopeIds = relationMapper.selectList(new LambdaQueryWrapper<TokenScope>()
.eq(TokenScope::getTokenId, token.getId()).eq(TokenScope::getSoftDelete, 0))
.stream().map(TokenScope::getScopeId).toList();
@@ -196,7 +214,9 @@ public class AdminTokenService {
.stream().map(AgentScope::getName).toList();
return new TokenView(token.getId(), token.getKeyPrefix(), token.getMemo(), token.getStatus(),
token.getPrincipalType(), token.getSubjectName(),
token.getExpireTime(), token.getLastUsedTime(), scopeIds, scopeNames);
token.getExpireTime(), token.getLastUsedTime(), scopeIds, scopeNames,
token.getCreateId(), issuer == null ? null : issuer.getAccount(),
issuer == null ? null : issuer.getName());
}
private void replaceScopes(Long tokenId, List<Long> scopeIds, Long adminId) {
@@ -252,6 +272,7 @@ public class AdminTokenService {
public record TokenView(Long id, String keyPrefix, String memo, Byte status,
String principalType, String subjectName, Date expireTime,
Date lastUsedTime, List<Long> scopeIds, List<String> scopeNames) {}
Date lastUsedTime, List<Long> scopeIds, List<String> scopeNames,
Long issuerId, String issuerAccount, String issuerName) {}
public record IssuedToken(String plaintext, TokenView token) {}
}
@@ -0,0 +1,178 @@
package me.iiv.agent.admin;
import me.iiv.agent.entity.svc.AdminUser;
import me.iiv.agent.mapper.svc.AdminUserMapper;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.web.server.ResponseStatusException;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
class AdminAccountServiceTest {
@Mock AdminUserMapper mapper;
@Mock AdminPasswordHasher hasher;
private AdminAccountService service() {
return new AdminAccountService(mapper, hasher);
}
@Test
void createHashesPasswordAndRecordsOperator() {
when(mapper.selectOne(any())).thenReturn(null);
when(hasher.hash("a-strong-password")).thenReturn("pbkdf2-hash");
when(mapper.insert(any(AdminUser.class))).thenAnswer(invocation -> {
invocation.<AdminUser>getArgument(0).setId(8L);
return 1;
});
AdminAccountService.AccountView view = service().create(
new AdminAccountService.AccountRequest("operator", "a-strong-password", "运营管理员", null), 1L);
ArgumentCaptor<AdminUser> captor = ArgumentCaptor.forClass(AdminUser.class);
verify(mapper).insert(captor.capture());
AdminUser stored = captor.getValue();
assertEquals("operator", stored.getAccount());
assertEquals("pbkdf2-hash", stored.getPasswordHash());
assertEquals(1L, stored.getCreateId());
assertEquals(1L, stored.getModifyId());
assertEquals((byte) 1, stored.getStatus());
assertEquals((byte) 0, stored.getSoftDelete());
assertEquals(8L, view.id());
assertEquals("operator", view.account());
}
@Test
void createRejectsDuplicateEvenWhenOldAccountWasDeleted() {
AdminUser deleted = new AdminUser();
deleted.setSoftDelete((byte) 1);
when(mapper.selectOne(any())).thenReturn(deleted);
assertThrows(ResponseStatusException.class, () -> service().create(
new AdminAccountService.AccountRequest("operator", "a-strong-password", "运营", null), 1L));
verify(mapper, never()).insert(any(AdminUser.class));
}
@Test
void updateWithBlankPasswordKeepsExistingHash() {
AdminUser current = activeAdmin(8L, "old-account");
when(mapper.selectById(8L)).thenReturn(current);
when(mapper.selectOne(any())).thenReturn(null);
service().update(8L, new AdminAccountService.AccountRequest(
"new-account", "", "新姓名", (byte) 1), 1L);
assertEquals("new-account", current.getAccount());
assertEquals("new-name-hash", current.getPasswordHash());
assertEquals("新姓名", current.getName());
assertEquals(1L, current.getModifyId());
verify(hasher, never()).hash(any());
verify(mapper).updateById(current);
}
@Test
void updateCanResetPassword() {
AdminUser current = activeAdmin(8L, "operator");
when(mapper.selectById(8L)).thenReturn(current);
when(mapper.selectOne(any())).thenReturn(null);
when(hasher.hash("another-strong-password")).thenReturn("new-hash");
service().update(8L, new AdminAccountService.AccountRequest(
"operator", "another-strong-password", "运营", (byte) 1), 1L);
assertEquals("new-hash", current.getPasswordHash());
}
@Test
void builtInAdminCannotBeRenamed() {
AdminUser current = activeAdmin(1L, "admin");
when(mapper.selectById(1L)).thenReturn(current);
when(mapper.selectOne(any())).thenReturn(null);
assertThrows(ResponseStatusException.class, () -> service().update(1L,
new AdminAccountService.AccountRequest("other-admin", "", "系统管理员", (byte) 1), 1L));
verify(mapper, never()).updateById(any(AdminUser.class));
}
@Test
void updateRejectsDisablingCurrentLoginAccount() {
AdminUser current = activeAdmin(8L, "operator");
when(mapper.selectById(8L)).thenReturn(current);
when(mapper.selectOne(any())).thenReturn(null);
assertThrows(ResponseStatusException.class, () -> service().update(8L,
new AdminAccountService.AccountRequest("operator", "", "运营", (byte) 0), 8L));
verify(mapper, never()).updateById(any(AdminUser.class));
}
@Test
void deleteRejectsCurrentLoginAccount() {
AdminUser current = activeAdmin(8L, "operator");
when(mapper.selectById(8L)).thenReturn(current);
assertThrows(ResponseStatusException.class, () -> service().delete(8L, 8L));
verify(mapper, never()).updateById(any(AdminUser.class));
}
@Test
void deleteRejectsLastActiveAdministrator() {
AdminUser current = activeAdmin(8L, "operator");
when(mapper.selectById(8L)).thenReturn(current);
when(mapper.selectCount(any())).thenReturn(0L);
assertThrows(ResponseStatusException.class, () -> service().delete(8L, 1L));
verify(mapper, never()).updateById(any(AdminUser.class));
}
@Test
void deleteSoftDeletesAndDisablesAccount() {
AdminUser current = activeAdmin(8L, "operator");
when(mapper.selectById(8L)).thenReturn(current);
when(mapper.selectCount(any())).thenReturn(1L);
service().delete(8L, 1L);
assertEquals((byte) 0, current.getStatus());
assertEquals((byte) 1, current.getSoftDelete());
assertEquals(1L, current.getModifyId());
verify(mapper).updateById(current);
}
@Test
void listNeverExposesPasswordHash() {
AdminUser admin = activeAdmin(8L, "operator");
admin.setPasswordHash("must-not-leak");
admin.setName("运营");
when(mapper.selectList(any())).thenReturn(List.of(admin));
List<AdminAccountService.AccountView> result = service().list();
assertEquals(1, result.size());
assertEquals("operator", result.get(0).account());
assertEquals("运营", result.get(0).name());
assertEquals(6, AdminAccountService.AccountView.class.getRecordComponents().length,
"AccountView 只应暴露 id/account/name/status/createTime/modifyTime");
}
private static AdminUser activeAdmin(Long id, String account) {
AdminUser admin = new AdminUser();
admin.setId(id);
admin.setAccount(account);
admin.setPasswordHash("new-name-hash");
admin.setName("管理员");
admin.setStatus((byte) 1);
admin.setSoftDelete((byte) 0);
return admin;
}
}
@@ -0,0 +1,39 @@
package me.iiv.agent.admin;
import me.iiv.agent.entity.svc.AdminUser;
import me.iiv.agent.mapper.svc.AdminUserMapper;
import org.junit.jupiter.api.Test;
import org.springframework.mock.web.MockFilterChain;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.mock.web.MockHttpSession;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class AdminSessionAccountTest {
@Test
void deletedAccountSessionIsRejected() throws Exception {
AdminUserMapper mapper = mock(AdminUserMapper.class);
AdminUser deleted = new AdminUser();
deleted.setId(1L);
deleted.setStatus((byte) 0);
deleted.setSoftDelete((byte) 1);
when(mapper.selectById(1L)).thenReturn(deleted);
AdminSessionFilter filter = new AdminSessionFilter(mapper);
MockHttpSession session = new MockHttpSession();
session.setAttribute(AdminSessionFilter.ADMIN_SESSION_ID, 1L);
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/api/admin/tools");
request.setSession(session);
MockHttpServletResponse response = new MockHttpServletResponse();
MockFilterChain chain = new MockFilterChain();
filter.doFilter(request, response, chain);
assertEquals(401, response.getStatus());
assertNull(chain.getRequest());
}
}
@@ -1,5 +1,8 @@
package me.iiv.agent.admin;
import me.iiv.agent.entity.svc.AdminUser;
import me.iiv.agent.mapper.svc.AdminUserMapper;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.mock.web.MockFilterChain;
import org.springframework.mock.web.MockHttpServletRequest;
@@ -9,10 +12,24 @@ import org.springframework.mock.web.MockHttpSession;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.mockito.Mockito.lenient;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class AdminSessionFilterTest {
private final AdminSessionFilter filter = new AdminSessionFilter();
private final AdminUserMapper mapper = mock(AdminUserMapper.class);
private final AdminSessionFilter filter = new AdminSessionFilter(mapper);
@BeforeEach
void setUp() {
AdminUser admin = new AdminUser();
admin.setId(1L);
admin.setAccount("admin");
admin.setStatus((byte) 1);
admin.setSoftDelete((byte) 0);
lenient().when(mapper.selectById(1L)).thenReturn(admin);
}
@Test
void protectedApiRequiresSession() throws Exception {
@@ -50,6 +67,39 @@ class AdminSessionFilterTest {
assertSame(request, chain.getRequest());
}
@Test
void accountManagementRejectsNonAdmin() throws Exception {
AdminUser operator = new AdminUser();
operator.setId(2L);
operator.setAccount("operator");
operator.setStatus((byte) 1);
operator.setSoftDelete((byte) 0);
when(mapper.selectById(2L)).thenReturn(operator);
MockHttpSession session = new MockHttpSession();
session.setAttribute(AdminSessionFilter.ADMIN_SESSION_ID, 2L);
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/api/admin/accounts");
request.setSession(session);
MockHttpServletResponse response = new MockHttpServletResponse();
MockFilterChain chain = new MockFilterChain();
filter.doFilter(request, response, chain);
assertEquals(403, response.getStatus());
assertNull(chain.getRequest());
}
@Test
void accountManagementAllowsAdmin() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/api/admin/accounts");
request.setSession(authenticatedSession());
MockHttpServletResponse response = new MockHttpServletResponse();
MockFilterChain chain = new MockFilterChain();
filter.doFilter(request, response, chain);
assertSame(request, chain.getRequest());
}
@Test
void mutationRequiresMatchingCsrfToken() throws Exception {
MockHttpSession session = authenticatedSession();
@@ -0,0 +1,67 @@
package me.iiv.agent.admin;
import me.iiv.agent.entity.svc.AdminUser;
import me.iiv.agent.entity.svc.AgentApiKey;
import me.iiv.agent.entity.svc.AgentScope;
import me.iiv.agent.entity.svc.TokenScope;
import me.iiv.agent.mapper.m0.UserMapper;
import me.iiv.agent.mapper.svc.AdminUserMapper;
import me.iiv.agent.mapper.svc.AgentApiKeyMapper;
import me.iiv.agent.mapper.svc.AgentScopeMapper;
import me.iiv.agent.mapper.svc.TokenScopeMapper;
import me.iiv.agent.security.TokenCipher;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyCollection;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
class AdminTokenIssuerTest {
@Mock UserMapper userMapper;
@Mock AgentApiKeyMapper tokenMapper;
@Mock TokenScopeMapper tokenScopeMapper;
@Mock AgentScopeMapper scopeMapper;
@Mock TokenCipher tokenCipher;
@Mock AdminUserMapper adminUserMapper;
@Test
void tokenListIncludesIssuingAdminAccountEvenAfterAccountDeletion() {
AgentApiKey token = new AgentApiKey();
token.setId(11L);
token.setUserId(7L);
token.setCreateId(3L);
token.setSoftDelete((byte) 0);
when(tokenMapper.selectList(any())).thenReturn(List.of(token));
TokenScope relation = new TokenScope();
relation.setTokenId(11L);
relation.setScopeId(5L);
relation.setSoftDelete((byte) 0);
when(tokenScopeMapper.selectList(any())).thenReturn(List.of(relation));
AgentScope scope = new AgentScope();
scope.setId(5L);
scope.setName("研发专用");
when(scopeMapper.selectList(any())).thenReturn(List.of(scope));
AdminUser issuer = new AdminUser();
issuer.setId(3L);
issuer.setAccount("wangheng");
issuer.setName("王恒");
issuer.setSoftDelete((byte) 1);
when(adminUserMapper.selectBatchIds(anyCollection())).thenReturn(List.of(issuer));
AdminTokenService service = new AdminTokenService(userMapper, tokenMapper,
tokenScopeMapper, scopeMapper, tokenCipher, adminUserMapper);
AdminTokenService.TokenView view = service.list(7L).get(0);
assertEquals(3L, view.issuerId());
assertEquals("wangheng", view.issuerAccount());
assertEquals("王恒", view.issuerName());
}
}
@@ -5,6 +5,7 @@ import me.iiv.agent.entity.svc.AgentApiKey;
import me.iiv.agent.entity.svc.AgentScope;
import me.iiv.agent.entity.svc.TokenScope;
import me.iiv.agent.mapper.m0.UserMapper;
import me.iiv.agent.mapper.svc.AdminUserMapper;
import me.iiv.agent.mapper.svc.AgentApiKeyMapper;
import me.iiv.agent.mapper.svc.AgentScopeMapper;
import me.iiv.agent.mapper.svc.TokenScopeMapper;
@@ -36,6 +37,7 @@ class AdminTokenServiceTest {
@Mock TokenScopeMapper tokenScopeMapper;
@Mock AgentScopeMapper scopeMapper;
@Mock TokenCipher tokenCipher;
@Mock AdminUserMapper adminUserMapper;
private User stubUser() {
User user = new User();
@@ -48,7 +50,8 @@ class AdminTokenServiceTest {
private AdminTokenService service() {
org.mockito.Mockito.lenient().when(tokenCipher.encrypt(any()))
.thenAnswer(invocation -> "cipher:" + invocation.getArgument(0));
return new AdminTokenService(userMapper, tokenMapper, tokenScopeMapper, scopeMapper, tokenCipher);
return new AdminTokenService(userMapper, tokenMapper, tokenScopeMapper, scopeMapper,
tokenCipher, adminUserMapper);
}
@Test
@@ -96,7 +96,7 @@ class OpenTokenServiceTest {
private static AdminTokenService.IssuedToken issuedToken(String plaintext) {
AdminTokenService.TokenView view = new AdminTokenService.TokenView(
12L, "xqak_efgh5678", "open-api 自动签发(operation)", (byte) 1,
"user", null, null, null, List.of(3L), List.of("运营"));
"user", null, null, null, List.of(3L), List.of("运营"), 0L, null, null);
return new AdminTokenService.IssuedToken(plaintext, view);
}
@@ -228,7 +228,7 @@ class OpenTokenServiceTest {
when(tokenService.findActiveServiceToken("xiaoqu-ai", 9L)).thenReturn(null);
AdminTokenService.TokenView view = new AdminTokenService.TokenView(
12L, "xqak_efgh5678", "open-api 服务签发(sync)", (byte) 1,
"service", "xiaoqu-ai", null, null, List.of(9L), List.of("数据同步"));
"service", "xiaoqu-ai", null, null, List.of(9L), List.of("数据同步"), 0L, null, null);
when(tokenService.issueServiceToken(eq("xiaoqu-ai"), anyString(), eq(9L), isNull(), eq(0L)))
.thenReturn(new AdminTokenService.IssuedToken("xqak_" + "c".repeat(48), view));
@@ -273,7 +273,7 @@ class OpenTokenServiceTest {
when(tokenService.findActiveServiceToken("xiaoqu-ai", 9L)).thenReturn(existing);
AdminTokenService.TokenView view = new AdminTokenService.TokenView(
12L, "xqak_efgh5678", "open-api 服务签发(sync)", (byte) 1,
"service", "xiaoqu-ai", null, null, List.of(9L), List.of("数据同步"));
"service", "xiaoqu-ai", null, null, List.of(9L), List.of("数据同步"), 0L, null, null);
when(tokenService.issueServiceToken(eq("xiaoqu-ai"), anyString(), eq(9L), isNull(), eq(0L)))
.thenReturn(new AdminTokenService.IssuedToken("xqak_" + "d".repeat(48), view));
@@ -330,7 +330,7 @@ class OpenTokenServiceTest {
when(tokenService.findActiveServiceToken("ops", 10L)).thenReturn(null);
AdminTokenService.TokenView view = new AdminTokenService.TokenView(
13L, "xqak_ops00000", "open-api 服务签发(ops-query)", (byte) 1,
"service", "ops", null, null, List.of(10L), List.of("运营查询"));
"service", "ops", null, null, List.of(10L), List.of("运营查询"), 0L, null, null);
when(tokenService.issueServiceToken(eq("ops"), anyString(), eq(10L), isNull(), eq(0L)))
.thenReturn(new AdminTokenService.IssuedToken("xqak_" + "e".repeat(48), view));