feat(多公司): 第二批 —— 登录带出公司身份、移人仅超管、启动期 DEFAULT 哨兵、列表公司列

company 模块落地(目录读写收窄 + 菜单闸门),并把公司维度接进四个已有出口:
- 登录/current-user 回包带 companyId/companyName,且取名失败不得挡住登录;
- 移人仅超管,且校验「创建人同公司或为超管」不变式(二期免改 77 处过滤点的前提);
- users.company_id 的 DEFAULT 由启动期哨兵盯着,多公司已上线仍未摘则打
  COMPANY_DEFAULT_STILL_PRESENT(ASCII 标记串,供 docker logs grep);
- 账号列表加 company_id/company_name 与可选按公司筛选:超管可筛任意公司,
  公司内 admin 传别家公司视为无结果(不报错也不越权)。

39 例护栏,29 条变异自证(首轮 25/28 咬死,两条存活都是用例侧的洞:
namesByIds 被 mock 掉所以内部去重从未被证明、contains("公司") 分不清闸门与
不变式;修补后 4/4 KILLED)。业务表零 DDL、零回填。
This commit is contained in:
2026-10-04 07:11:13 +08:00
parent 5633898a0d
commit 061147c603
33 changed files with 2454 additions and 12 deletions
@@ -3,6 +3,7 @@ package com.nanri.aiimage.modules.admin.controller;
import com.nanri.aiimage.common.api.ApiResponse;
import com.nanri.aiimage.common.security.AdminAuthSupport;
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
import com.nanri.aiimage.modules.company.service.CompanyService;
import com.nanri.aiimage.modules.permission.model.vo.PermissionMenuItemVo;
import com.nanri.aiimage.modules.permission.service.PermissionMenuService;
import com.nanri.aiimage.modules.permission.service.support.AdminMenuTreeBuilder;
@@ -36,6 +37,7 @@ public class AdminConsoleController {
private final AdminAuthSupport adminAuthSupport;
private final PermissionMenuService permissionMenuService;
private final CompanyService companyService;
@GetMapping("/")
@Operation(summary = "根路径跳管理后台", hidden = true)
@@ -69,6 +71,10 @@ public class AdminConsoleController {
item.put("id", operator.getId());
item.put("username", operator.getUsername() == null ? "" : operator.getUsername());
item.put("role", adminAuthSupport.currentRole(operator));
// 键名固定 camelCase:session.ts 把 item 原样当 AdminUser 用,没有字段映射层,
// 拼错只会让顶栏静默少一行字(前端 || '' 兜底),不会报错。
item.put("companyId", operator.getCompanyId());
item.put("companyName", companyService.nameOrEmpty(operator.getCompanyId()));
return ApiResponse.success(Map.of("item", item));
}
@@ -39,11 +39,12 @@ 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,
@RequestParam(name = "role", required = false) String role) {
@RequestParam(name = "role", required = false) String role,
@RequestParam(name = "company_id", required = false) Long companyId) {
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, role);
AdminUserListVo vo = adminUserService.listUsers(currentUser, page, pageSize, kw, filterCreatedBy, role, companyId);
return ApiResponse.success(vo);
}
@@ -10,5 +10,6 @@ public class AdminUserCreateRequest {
private String password;
private String role;
private Long createdById;
private Long companyId;
private List<Long> columnIds;
}
@@ -9,4 +9,6 @@ public class AdminUserUpdateRequest {
private String password;
private String role;
private List<Long> columnIds;
/** 移人目标公司(V143 §2.2,仅超管可用);null 或与账号现公司相同都表示「不动」。 */
private Long companyId;
}
@@ -12,6 +12,10 @@ public class AdminUserItemVo {
private String role;
@JsonProperty("created_by_id")
private Long createdById;
@JsonProperty("company_id")
private Long companyId;
@JsonProperty("company_name")
private String companyName;
@JsonProperty("creator_username")
private String creatorUsername;
@JsonProperty("created_at")
@@ -14,6 +14,7 @@ import com.nanri.aiimage.modules.auth.util.WerkzeugPasswordEncoder;
import com.nanri.aiimage.common.mapper.AdminUserMapper;
import com.nanri.aiimage.modules.permission.model.dto.UserColumnPermissionUpdateRequest;
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
import com.nanri.aiimage.modules.company.service.CompanyService;
import com.nanri.aiimage.modules.permission.service.PermissionMenuService;
import com.nanri.aiimage.modules.admin.spi.UserSecretCleanupPort;
import lombok.RequiredArgsConstructor;
@@ -44,9 +45,11 @@ public class AdminUserService {
private final AdminAuthSupport adminAuthSupport;
private final PermissionMenuService permissionMenuService;
private final UserSecretCleanupPort userSecretCleanupPort;
private final CompanyService companyService;
public AdminUserListVo listUsers(AdminUserEntity currentUser, Integer page, Integer pageSize,
String username, Long createdById, String roleFilter) {
String username, Long createdById, String roleFilter,
Long companyIdFilter) {
String role = adminAuthSupport.currentRole(currentUser);
if (role == null) {
throw new BusinessException(403, "需要管理员权限");
@@ -68,13 +71,24 @@ public class AdminUserService {
if (!roleFilterValue.isEmpty()) {
query.eq(AdminUserEntity::getRole, roleFilterValue);
}
if ("super_admin".equals(role)) {
boolean isSuperAdmin = "super_admin".equals(role);
if (companyIdFilter != null && !isSuperAdmin) {
// 公司内管理员:筛自己公司 = 不加条件(他的可见范围本来就只有本公司),
// 筛别家公司 = 直接空页。这里故意不报错也不越权(设计文档 §2.3)。
if (!companyIdFilter.equals(currentUser.getCompanyId())) {
return emptyListVo(currentUser, role, safePage, safeSize);
}
}
if (isSuperAdmin) {
if (!kw.isEmpty()) {
query.like(AdminUserEntity::getUsername, kw);
}
if (filterCreatedBy != null) {
query.eq(AdminUserEntity::getCreatedById, filterCreatedBy);
}
if (companyIdFilter != null) {
query.eq(AdminUserEntity::getCompanyId, companyIdFilter);
}
} else {
Long adminId = currentUser.getId();
query.and(w -> w
@@ -94,8 +108,9 @@ public class AdminUserService {
List<AdminUserEntity> rows = adminUserMapper.selectList(query);
Map<Long, String> creatorMap = loadCreatorMap(rows);
Map<Long, String> companyMap = loadCompanyNameMap(rows);
List<AdminUserItemVo> items = rows.stream().map(r -> toItem(r, creatorMap)).toList();
List<AdminUserItemVo> items = rows.stream().map(r -> toItem(r, creatorMap, companyMap)).toList();
List<AdminBriefVo> admins = "super_admin".equals(role)
? adminUserMapper.selectList(new LambdaQueryWrapper<AdminUserEntity>()
.eq(AdminUserEntity::getRole, "admin")
@@ -166,6 +181,7 @@ public class AdminUserService {
entity.setIsAdmin(isAdmin);
entity.setRole(wantRole);
entity.setCreatedById(wantCreatedBy);
entity.setCompanyId(resolveTargetCompanyId(role, currentUser, request.getCompanyId()));
try {
adminUserMapper.insert(entity);
} catch (DuplicateKeyException e) {
@@ -175,6 +191,68 @@ public class AdminUserService {
return entity.getId();
}
/**
* 建号落哪家公司(设计文档 §2.2,与 createdById 同构):超管可指定任意启用中的公司,
* 其余角色只能落自己所属公司——显式传别家即 403,不静默改写。
*
* <p>永远返回一个具体值并写进实体:列 DEFAULT 1 只为发布期的旧 jar 存在(§8.2),
* 新代码不靠它,否则第二家公司开通后每个未传公司的建号都会被静默塞进厦门米椿花。</p>
*/
private Long resolveTargetCompanyId(String operatorRole, AdminUserEntity operator, Long requestedCompanyId) {
if (!"super_admin".equals(operatorRole)) {
if (requestedCompanyId != null && !requestedCompanyId.equals(operator.getCompanyId())) {
throw new BusinessException(403, "只能在本公司名下创建账号");
}
return operator.getCompanyId();
}
if (requestedCompanyId == null) {
return operator.getCompanyId();
}
companyService.requireActive(requestedCompanyId);
return requestedCompanyId;
}
/**
* 移人(设计文档 §2.2):返回要把账号移去的公司 id,返回 null 表示「这次没动公司」。
*
* <p>只有超管能移;传的正好是账号现属公司按"没动"处理(跟建号那条同构,别把幂等请求判成越权)。
* 公司内 admin 传别家一律 403,不静默改写——静默改写会让操作者以为移成功了。</p>
*/
private Long resolveCompanyMove(String operatorRole, AdminUserEntity target, Long requestedCompanyId) {
if (requestedCompanyId == null || requestedCompanyId.equals(target.getCompanyId())) {
return null;
}
if (!"super_admin".equals(operatorRole)) {
throw new BusinessException(403, "只有超级管理员可以把账号移到其他公司");
}
companyService.requireActive(requestedCompanyId);
return requestedCompanyId;
}
/**
* 移人之后的不变式:账号的 {@code created_by_id} 必须与它同一家公司,除非创建人是超管。
*
* <p>这条是二期不回改 77 处 {@code eq(getUserId, userId)} 过滤点的前提(§7.2):数据按账号归属,
* 而公司内 admin 的可编辑范围判的是 {@code created_by_id}。一旦允许把账号移进一家它创建人不在的公司,
* "同公司"和"同一人"两套口径就会交叉,越权只能逐出口重新补。</p>
*/
private void ensureCreatorSharesCompany(AdminUserEntity target, Long newCompanyId) {
Long createdById = target.getCreatedById();
if (createdById == null) {
return;
}
AdminUserEntity creator = adminUserMapper.selectById(createdById);
if (creator == null) {
throw new BusinessException(403, "该账号的创建人已不存在,无法确认同公司,不能移入其他公司");
}
if ("super_admin".equals(creator.getRole())) {
return;
}
if (!newCompanyId.equals(creator.getCompanyId())) {
throw new BusinessException(403, "只能把账号移到其创建人所在的公司");
}
}
@Transactional
public void updateUser(AdminUserEntity currentUser, Long uid, AdminUserUpdateRequest request) {
String role = adminAuthSupport.currentRole(currentUser);
@@ -187,7 +265,8 @@ public class AdminUserService {
if ((password == null || password.isEmpty())
&& (wantRole == null || wantRole.isEmpty())
&& request.getColumnIds() == null) {
&& request.getColumnIds() == null
&& request.getCompanyId() == null) {
throw new BusinessException("请提供要修改的内容");
}
@@ -214,9 +293,19 @@ public class AdminUserService {
}
}
// 移人先于写库:先确认目标公司可用,再确认 created_by_id 不变式没被破坏
Long moveCompanyId = resolveCompanyMove(role, target, request.getCompanyId());
if (moveCompanyId != null) {
ensureCreatorSharesCompany(target, moveCompanyId);
}
LambdaUpdateWrapper<AdminUserEntity> update = new LambdaUpdateWrapper<AdminUserEntity>()
.eq(AdminUserEntity::getId, uid);
boolean dirty = false;
if (moveCompanyId != null) {
update.set(AdminUserEntity::getCompanyId, moveCompanyId);
dirty = true;
}
if (password != null && !password.isEmpty()) {
if (password.length() < 6) {
throw new BusinessException("密码至少6个字符");
@@ -307,6 +396,31 @@ public class AdminUserService {
log.info("[admin-user] 用户已删除 uid={} 级联清理密钥行={}", uid, secretRows);
}
private Map<Long, String> loadCompanyNameMap(List<AdminUserEntity> rows) {
Set<Long> companyIds = new LinkedHashSet<>();
for (AdminUserEntity r : rows) {
if (r.getCompanyId() != null) {
companyIds.add(r.getCompanyId());
}
}
// 空页不去查公司表;一次批量查而不是每行一次(一行一次就是 N+1)
return companyIds.isEmpty() ? Map.of() : companyService.namesByIds(companyIds);
}
/** 公司内管理员筛了别家公司:返回一个"这一页什么都没有"的正常响应,不报错、也不去碰表。 */
private AdminUserListVo emptyListVo(AdminUserEntity currentUser, String role, int page, int pageSize) {
AdminUserListVo vo = new AdminUserListVo();
vo.setItems(List.of());
vo.setTotal(0L);
vo.setPage(page);
vo.setPageSize(pageSize);
vo.setCurrentUserRole(role);
vo.setCurrentUserId(currentUser.getId());
vo.setCurrentUserUsername(currentUser.getUsername() == null ? "" : currentUser.getUsername());
vo.setAdmins(List.of());
return vo;
}
private Map<Long, String> loadCreatorMap(List<AdminUserEntity> rows) {
Set<Long> creatorIds = new LinkedHashSet<>();
for (AdminUserEntity r : rows) {
@@ -326,7 +440,8 @@ public class AdminUserService {
return map;
}
private AdminUserItemVo toItem(AdminUserEntity entity, Map<Long, String> creatorMap) {
private AdminUserItemVo toItem(AdminUserEntity entity, Map<Long, String> creatorMap,
Map<Long, String> companyMap) {
AdminUserItemVo vo = new AdminUserItemVo();
vo.setId(entity.getId());
vo.setUsername(entity.getUsername());
@@ -336,6 +451,10 @@ public class AdminUserService {
// 不可变 Map(Map.of) 的 getOrDefault 不允许 null key:createdById 为 null 时直接空串。
Long creatorId = entity.getCreatedById();
vo.setCreatorUsername(creatorId == null ? "" : creatorMap.getOrDefault(creatorId, ""));
Long companyId = entity.getCompanyId();
vo.setCompanyId(companyId);
// 账号挂着公司表里查不到的 id(脏数据/回滚残留)时留空串,前端显示 '-',整页不能因此 500
vo.setCompanyName(companyId == null ? "" : companyMap.getOrDefault(companyId, ""));
LocalDateTime createdAt = entity.getCreatedAt();
vo.setCreatedAt(createdAt == null ? "" : createdAt.format(CREATED_AT_FORMATTER));
LocalDateTime updatedAt = entity.getUpdatedAt();