feat(admin): A1 管理后台收敛 Java 单后台完整实现并修复 guard 误拦内部令牌

- Java 补齐后台全部迁移差集:shopduplicatecheck 店铺数据重复检查模块(V108 扫描表+查询/扫描服务)、
  PinyinAbbrUtil 拼音缩写、ImageHistory 接口调整为内部可用、AdminUser 支持内部令牌操作并放宽列表上限
- Flask 后台 admin_api.py 路由收敛转发 Java、admin.html/admin.js 适配新后台形态
- AdminApiGuardFilter 对可信 X-Internal-Token 放行(controller 自校验兜底),修复客户端仅凭
  内部令牌调用 /api/admin/shop-manages/credential 被误拦 401
- 测试:AdminApiGuardFilterTest 补可信/假令牌用例;AdminUserServiceTest 补菜单权限 mock;
  shopduplicatecheck 新增查询/聚合/CSV 单测
This commit is contained in:
2026-09-04 11:30:09 +08:00
parent 1a3d46ac45
commit 25969406e6
43 changed files with 3071 additions and 1318 deletions
@@ -39,7 +39,7 @@ public class AdminUserController {
@RequestParam(name = "search", required = false) String search,
@RequestParam(name = "created_by_id", required = false) Long createdById,
@RequestParam(name = "admin_id", required = false) Long adminId) {
AdminUserEntity currentUser = adminAuthSupport.requireAdmin(request);
AdminUserEntity currentUser = adminAuthSupport.requireAdminOrInternal(request);
String kw = (username == null || username.isBlank()) ? search : username;
Long filterCreatedBy = createdById != null ? createdById : adminId;
AdminUserListVo vo = adminUserService.listUsers(currentUser, page, pageSize, kw, filterCreatedBy);
@@ -50,7 +50,7 @@ public class AdminUserController {
@Operation(summary = "创建用户")
public ApiResponse<Long> createUser(HttpServletRequest request,
@RequestBody AdminUserCreateRequest body) {
AdminUserEntity currentUser = adminAuthSupport.requireAdmin(request);
AdminUserEntity currentUser = adminAuthSupport.requireAdminOrInternal(request);
Long userId = adminUserService.createUser(currentUser, body);
return ApiResponse.success("用户创建成功", userId);
}
@@ -60,7 +60,7 @@ public class AdminUserController {
public ApiResponse<Void> updateUser(HttpServletRequest request,
@PathVariable Long uid,
@RequestBody AdminUserUpdateRequest body) {
AdminUserEntity currentUser = adminAuthSupport.requireAdmin(request);
AdminUserEntity currentUser = adminAuthSupport.requireAdminOrInternal(request);
adminUserService.updateUser(currentUser, uid, body);
return ApiResponse.success("更新成功", null);
}
@@ -69,7 +69,7 @@ public class AdminUserController {
@Operation(summary = "删除用户")
public ApiResponse<Void> deleteUser(HttpServletRequest request,
@PathVariable Long uid) {
AdminUserEntity currentUser = adminAuthSupport.requireAdmin(request);
AdminUserEntity currentUser = adminAuthSupport.requireAdminOrInternal(request);
adminUserService.deleteUser(currentUser, uid);
return ApiResponse.success("删除成功", null);
}
@@ -16,4 +16,6 @@ public class AdminUserItemVo {
private String creatorUsername;
@JsonProperty("created_at")
private String createdAt;
@JsonProperty("pinyin_abbr")
private String pinyinAbbr;
}
@@ -14,5 +14,9 @@ public class AdminUserListVo {
private Integer pageSize;
@JsonProperty("current_user_role")
private String currentUserRole;
@JsonProperty("current_user_id")
private Long currentUserId;
@JsonProperty("current_user_username")
private String currentUserUsername;
private List<AdminBriefVo> admins;
}
@@ -9,6 +9,7 @@ import com.nanri.aiimage.modules.admin.model.vo.AdminBriefVo;
import com.nanri.aiimage.modules.admin.model.vo.AdminUserItemVo;
import com.nanri.aiimage.modules.admin.model.vo.AdminUserListVo;
import com.nanri.aiimage.modules.admin.support.AdminAuthSupport;
import com.nanri.aiimage.modules.admin.util.PinyinAbbrUtil;
import com.nanri.aiimage.modules.auth.util.WerkzeugPasswordEncoder;
import com.nanri.aiimage.modules.permission.mapper.AdminUserMapper;
import com.nanri.aiimage.modules.permission.model.dto.UserColumnPermissionUpdateRequest;
@@ -46,10 +47,14 @@ public class AdminUserService {
if (role == null) {
throw new BusinessException(403, "需要管理员权限");
}
// 用户列表被多个后台页面用作用户选择器,权限按 Flask 的宽菜单 OR 预检(任一后台菜单可见即可拉取)
ensureAdminUsersMenuAccess(currentUser, List.of(
"admin_users", "admin_history", "admin_shop_manage", "admin_skip_price_asin",
"admin_query_asin", "admin_dedupe_total_data", "admin_invalid_asin_data"));
int safePage = page == null || page < 1 ? 1 : page;
int safeSize = pageSize == null ? 15 : pageSize;
if (safeSize < 5) safeSize = 5;
if (safeSize > 50) safeSize = 50;
if (safeSize > 999) safeSize = 999;
String kw = username == null ? "" : username.trim();
Long filterCreatedBy = "super_admin".equals(role) ? createdById : null;
@@ -97,6 +102,8 @@ public class AdminUserService {
vo.setPage(safePage);
vo.setPageSize(safeSize);
vo.setCurrentUserRole(role);
vo.setCurrentUserId(currentUser.getId());
vo.setCurrentUserUsername(currentUser.getUsername() == null ? "" : currentUser.getUsername());
vo.setAdmins(admins);
return vo;
}
@@ -107,6 +114,7 @@ public class AdminUserService {
if (role == null) {
throw new BusinessException(403, "需要管理员权限");
}
ensureAdminUsersMenuAccess(currentUser, List.of("admin_users"));
String username = request.getUsername() == null ? "" : request.getUsername().trim();
String password = request.getPassword() == null ? "" : request.getPassword();
String wantRole = request.getRole() == null ? "normal" : request.getRole().trim();
@@ -165,6 +173,7 @@ public class AdminUserService {
if (role == null) {
throw new BusinessException(403, "需要管理员权限");
}
ensureAdminUsersMenuAccess(currentUser, List.of("admin_users"));
String password = request.getPassword();
String wantRole = request.getRole() == null ? null : request.getRole().trim();
@@ -233,6 +242,7 @@ public class AdminUserService {
if (role == null) {
throw new BusinessException(403, "需要管理员权限");
}
ensureAdminUsersMenuAccess(currentUser, List.of("admin_users"));
if (currentUser.getId().equals(uid)) {
throw new BusinessException("不能删除当前登录账号");
}
@@ -284,6 +294,13 @@ public class AdminUserService {
vo.setCreatorUsername(creatorMap.getOrDefault(entity.getCreatedById(), ""));
LocalDateTime createdAt = entity.getCreatedAt();
vo.setCreatedAt(createdAt == null ? "" : createdAt.format(CREATED_AT_FORMATTER));
vo.setPinyinAbbr(PinyinAbbrUtil.abbr(entity.getUsername()));
return vo;
}
private void ensureAdminUsersMenuAccess(AdminUserEntity operator, List<String> columnKeys) {
if (!permissionMenuService.hasAnyAdminMenu(operator, columnKeys)) {
throw new BusinessException(403, "无权访问用户管理模块");
}
}
}
@@ -12,6 +12,11 @@ import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import com.nanri.aiimage.modules.auth.config.AuthProperties;
import org.springframework.beans.factory.annotation.Value;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
@Component
@RequiredArgsConstructor
@@ -21,6 +26,12 @@ public class AdminAuthSupport {
private final AdminUserMapper adminUserMapper;
private final AuthProperties authProperties;
@Value("${aiimage.security.internal-token:}")
private String internalToken;
@Value("${aiimage.security.internal-token-file:}")
private String internalTokenFile;
/** 解析当前请求的用户;token 缺失或无效抛 401。 */
public AdminUserEntity requireUser(HttpServletRequest request) {
String token = resolveToken(request);
@@ -73,6 +84,118 @@ public class AdminAuthSupport {
return null;
}
/** JWT 优先;无 JWT 时以可信内部代理身份(X-Internal-Token + operatorId)回退,仍要求管理员角色。 */
public AdminUserEntity requireAdminOrInternal(HttpServletRequest request) {
try {
return requireAdmin(request);
} catch (BusinessException authFailure) {
AdminUserEntity internalOperator = resolveInternalOperator(request, true);
if (internalOperator != null) {
return internalOperator;
}
throw authFailure;
}
}
/** JWT 优先;无 JWT 时以可信内部代理身份回退(仅要求用户存在)。 */
public AdminUserEntity requireUserOrInternal(HttpServletRequest request) {
try {
return requireUser(request);
} catch (BusinessException authFailure) {
AdminUserEntity internalOperator = resolveInternalOperator(request, false);
if (internalOperator != null) {
return internalOperator;
}
throw authFailure;
}
}
/**
* Flask 传统后台用 session 登录、无法签发 Java JWT,只能凭共享密钥
* (显式配置或每个用户的本地 token 文件)标识已认证管理员。这里仍会
* 回库校验管理员角色,superAdmin 查询标志不参与判定。
*/
private AdminUserEntity resolveInternalOperator(HttpServletRequest request, boolean requireAdmin) {
if (!isTrustedInternalRequest(request)) {
return null;
}
String rawOperatorId = request.getParameter("operatorId");
if (rawOperatorId == null || rawOperatorId.isBlank()) {
rawOperatorId = request.getParameter("operator_id");
}
if (rawOperatorId == null || rawOperatorId.isBlank()) {
return null;
}
try {
Long operatorId = Long.parseLong(rawOperatorId.trim());
AdminUserEntity operator = adminUserMapper.selectById(operatorId);
if (operator == null) {
return null;
}
if (requireAdmin && currentRole(operator) == null) {
return null;
}
return operator;
} catch (NumberFormatException ex) {
return null;
}
}
private boolean isTrustedInternalRequest(HttpServletRequest request) {
String suppliedToken = request.getHeader("X-Internal-Token");
String expectedToken = resolveExpectedInternalToken();
if (expectedToken.isBlank() || suppliedToken == null || suppliedToken.isBlank()) {
return false;
}
return expectedToken.equals(suppliedToken.trim());
}
/**
* 仅判断请求是否携带可信内部令牌(不要求 operatorId)。供 AdminApiGuardFilter
* 在兜底鉴权前放行内部自动化调用(仅凭 X-Internal-Token 即鉴权的端点,如
* /api/admin/shop-manages/credential 由 controller 自校验令牌),
* 避免 guard 把合法的内部调用误拦为 401。
*/
public boolean isTrustedInternalToken(HttpServletRequest request) {
return isTrustedInternalRequest(request);
}
private String resolveExpectedInternalToken() {
if (internalToken != null && !internalToken.isBlank()) {
return internalToken.trim();
}
Path path = resolveInternalTokenFile();
if (path == null || !Files.isRegularFile(path)) {
return "";
}
try {
return Files.readString(path, StandardCharsets.UTF_8).trim();
} catch (Exception ignored) {
return "";
}
}
private Path resolveInternalTokenFile() {
String configuredPath = internalTokenFile == null ? "" : internalTokenFile.trim();
if (!configuredPath.isEmpty()) {
if (configuredPath.equals("~") || configuredPath.startsWith("~/") || configuredPath.startsWith("~\\")) {
String userHome = System.getProperty("user.home", "").trim();
if (userHome.isEmpty()) {
return null;
}
configuredPath = configuredPath.length() == 1
? userHome
: Path.of(userHome, configuredPath.substring(2)).toString();
}
Path configuredTokenPath = Path.of(configuredPath);
return configuredTokenPath.isAbsolute() ? configuredTokenPath.normalize() : null;
}
String userHome = System.getProperty("user.home", "").trim();
return userHome.isEmpty()
? null
: Path.of(userHome, ".aiimage", "internal-token").toAbsolutePath().normalize();
}
private String resolveToken(HttpServletRequest request) {
String authHeader = request.getHeader(HttpHeaders.AUTHORIZATION);
if (authHeader != null && authHeader.startsWith("Bearer ")) {
@@ -0,0 +1,72 @@
package com.nanri.aiimage.modules.admin.util;
/**
* 用户名拼音首字母缩写(分组管理/通讯录用),无第三方依赖。
* 与 Python backend/blueprints/admin_api.py 的 _username_pinyin_abbr 语义保持一致:
* GB2312 区位码按拼音音序排列,用码位区间判定首字母;仅覆盖 GB2312 汉字。
*/
public final class PinyinAbbrUtil {
private static final char[] PYINYIN_LETTERS = {
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M',
'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'W', 'X', 'Y', 'Z'
};
private static final int[] PYINYIN_BOUNDS = {
0xB0A1, 0xB0C5, 0xB2C1, 0xB4EE, 0xB6EA, 0xB7A2, 0xB8C1, 0xB9FE,
0xBBF7, 0xBFA6, 0xC0AC, 0xC2E8, 0xC4C3, 0xC5B6, 0xC5BE, 0xC6DA,
0xC8BB, 0xC8F6, 0xCBFA, 0xCDDA, 0xCEF4, 0xD1B9, 0xD4D1
};
private static final int PYINYIN_BOUNDS_END = 0xF7FF;
private PinyinAbbrUtil() {
}
/** 返回用户名各字符的拼音首字母串('张伟恒' -> 'ZWH'),空输入或非 GB2312 汉字返回 '#'。 */
public static String abbr(String username) {
if (username == null) {
return "#";
}
String name = username.trim();
if (name.isEmpty()) {
return "#";
}
StringBuilder sb = new StringBuilder(name.length());
for (int i = 0; i < name.length(); i++) {
sb.append(initial(name.charAt(i)));
}
return sb.toString();
}
private static char initial(char c) {
if (c >= '0' && c <= '9') {
return c;
}
if (c >= 'A' && c <= 'Z') {
return c;
}
if (c >= 'a' && c <= 'z') {
return (char) (c - 32);
}
if (c < 0x4E00 || c > 0x9FA5) {
return '#';
}
try {
byte[] gb = String.valueOf(c).getBytes("GB2312");
if (gb.length != 2) {
return '#';
}
int low = ((gb[0] & 0xFF) << 8) | (gb[1] & 0xFF);
if (low < 0xB0A1 || low >= PYINYIN_BOUNDS_END) {
return '#';
}
for (int i = PYINYIN_LETTERS.length - 1; i >= 0; i--) {
if (low >= PYINYIN_BOUNDS[i]) {
return PYINYIN_LETTERS[i];
}
}
return '#';
} catch (Exception e) {
return '#';
}
}
}