feat(公司tab): 店铺管理与数据权限分组按成员集筛, 凭据按 id 补读闸门
Task 11: ShopManageController.page / listGroups 接 DataReadScope.readScope, 把 company_id 算出的成员集当参数传给 service(controller 层收口, service 手上 只有 operatorId+布尔); ShopManageGroupService.list 增加 companyMemberIds 腿。 凭据 getCredentialById 的闸门用与 page() 同形的尺子(created_by_id IN creators OR group_id IN groups),不是账号集合 —— 后者表达不了分组那一腿, 会把列表看得见 的行读凭据时 403 掉, 那是把正当访问静默删掉。 新增 testutil/SourceScan 供源码扫描式护栏取文(找不到方法必须抛, 不许返回空串恒绿)。 前端两页接 tab: companyId 取 companyTab.requestCompanyId, 并 watch activeId 重载; G1 登记表给 admin_shop_manage 钉两条发送点(白名单 builder 故意不收 companyId)。 写侧入口一律不收 company_id, 由 ShopManageServiceTest 逐方法反向钉住。
This commit is contained in:
+3
-1
@@ -3,6 +3,7 @@ package com.nanri.aiimage.modules.shopkey.controller;
|
||||
import com.nanri.aiimage.common.api.ApiResponse;
|
||||
import com.nanri.aiimage.common.exception.BusinessException;
|
||||
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
|
||||
import com.nanri.aiimage.common.service.DataReadScope;
|
||||
import com.nanri.aiimage.common.security.AdminAuthSupport;
|
||||
import com.nanri.aiimage.modules.shopkey.model.vo.ShopManageCredentialVo;
|
||||
import com.nanri.aiimage.modules.shopkey.service.ShopManageGroupService;
|
||||
@@ -30,10 +31,11 @@ class ShopManageCredentialAuthTest {
|
||||
private final ShopManageService shopManageService = mock(ShopManageService.class);
|
||||
private final ShopManageGroupService shopManageGroupService = mock(ShopManageGroupService.class);
|
||||
private final AdminAuthSupport adminAuthSupport = mock(AdminAuthSupport.class);
|
||||
private final DataReadScope dataReadScope = mock(DataReadScope.class);
|
||||
private final HttpServletRequest request = mock(HttpServletRequest.class);
|
||||
|
||||
private ShopManageController newController() {
|
||||
return new ShopManageController(shopManageService, shopManageGroupService, adminAuthSupport);
|
||||
return new ShopManageController(shopManageService, shopManageGroupService, adminAuthSupport, dataReadScope);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+94
@@ -1,19 +1,35 @@
|
||||
package com.nanri.aiimage.modules.shopkey.service;
|
||||
|
||||
import com.baomidou.mybatisplus.core.MybatisConfiguration;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
|
||||
import com.nanri.aiimage.common.exception.BusinessException;
|
||||
import com.nanri.aiimage.common.model.entity.ShopManageGroupEntity;
|
||||
import com.nanri.aiimage.common.security.ShopCredentialCryptoService;
|
||||
import com.nanri.aiimage.modules.shopkey.mapper.ShopManageMapper;
|
||||
import com.nanri.aiimage.modules.shopkey.model.entity.ShopManageEntity;
|
||||
import com.nanri.aiimage.testutil.SourceScan;
|
||||
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.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
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.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertSame;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
@@ -29,6 +45,15 @@ class ShopManageServiceTest {
|
||||
@InjectMocks
|
||||
private ShopManageService service;
|
||||
|
||||
/** getSqlSegment() 解析 lambda 靠 TableInfo 缓存,单测没有 Spring 容器去建它,不初始化就抛 "can not find lambda cache"。 */
|
||||
@BeforeEach
|
||||
void initTableInfo() {
|
||||
TableInfoHelper.initTableInfo(
|
||||
new MapperBuilderAssistant(new MybatisConfiguration(), ""), ShopManageEntity.class);
|
||||
TableInfoHelper.initTableInfo(
|
||||
new MapperBuilderAssistant(new MybatisConfiguration(), ""), ShopManageGroupEntity.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
void requireShopByNameReturnsManagedShop() {
|
||||
ShopManageEntity entity = new ShopManageEntity();
|
||||
@@ -47,4 +72,73 @@ class ShopManageServiceTest {
|
||||
|
||||
assertEquals("后台店铺管理中未找到店铺:缺失店铺,请先添加店铺信息", exception.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("读:超管选了公司 ⇒ created_by_id 落进成员集;非超管不叠这一条")
|
||||
void superAdminPageNarrowsToCompanyMembers() {
|
||||
when(shopManageMapper.selectCount(any())).thenReturn(1L);
|
||||
when(shopManageMapper.selectList(any())).thenReturn(List.of());
|
||||
|
||||
service.page(1L, 15L, null, null, 1L, true, List.of(11L, 12L));
|
||||
|
||||
ArgumentCaptor<LambdaQueryWrapper<ShopManageEntity>> captor =
|
||||
ArgumentCaptor.forClass(LambdaQueryWrapper.class);
|
||||
verify(shopManageMapper).selectCount(captor.capture());
|
||||
// 值在 paramNameValuePairs 里,segment 里只有 MPGENVAL 占位 ⇒ 结构从 segment 读、值从 pairs 读。
|
||||
assertThat(captor.getValue().getSqlSegment()).contains("created_by_id").contains("IN (");
|
||||
assertThat(captor.getValue().getParamNameValuePairs().values()).contains(11L, 12L);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("凭据:非超管读「创建人不认识、分组也不认识」的行 ⇒ 403(§6.1 列表筛了按 id 照读)")
|
||||
void credentialByIdRejectsRowOutsideBothVisibleSets() {
|
||||
when(shopManageMapper.selectById(77L)).thenReturn(shop(77L, 999L, 7L));
|
||||
when(shopManageGroupService.listAccessibleCreatorUserIds(2L, false)).thenReturn(Set.of(11L, 12L));
|
||||
when(shopManageGroupService.listAccessibleGroupIds(2L, false)).thenReturn(Set.of());
|
||||
|
||||
assertThatThrownBy(() -> service.getCredentialById(77L, 2L, false))
|
||||
.isInstanceOf(BusinessException.class)
|
||||
.hasFieldOrPropertyWithValue("code", 403);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("凭据:店铺建在可访问分组里、创建人却不在我的账号集 ⇒ 必须 200(闸门用列表那把尺子,不是账号集合)")
|
||||
void credentialByIdKeepsGroupVisibleRowsReadable() {
|
||||
when(shopManageMapper.selectById(78L)).thenReturn(shop(78L, 999L, 5L));
|
||||
when(shopManageGroupService.listAccessibleCreatorUserIds(2L, false)).thenReturn(Set.of(11L));
|
||||
when(shopManageGroupService.listAccessibleGroupIds(2L, false)).thenReturn(Set.of(5L));
|
||||
|
||||
// 这一支是防误伤的正样本:把它删掉,下一轮"改成按账号集合卡"就没有任何尺子看得见。
|
||||
assertThatCode(() -> service.getCredentialById(78L, 2L, false)).doesNotThrowAnyException();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("凭据:超管不查可见集(今天不筛、tab 也不是安全边界;短路写了就红在 NPE 上)")
|
||||
void credentialByIdStaysUnfilteredForSuperAdmin() {
|
||||
when(shopManageMapper.selectById(79L)).thenReturn(shop(79L, 999L, 7L));
|
||||
|
||||
assertThatCode(() -> service.getCredentialById(79L, 1L, true)).doesNotThrowAnyException();
|
||||
}
|
||||
|
||||
private static ShopManageEntity shop(long id, Long createdById, Long groupId) {
|
||||
ShopManageEntity entity = new ShopManageEntity();
|
||||
entity.setId(id);
|
||||
entity.setCreatedById(createdById);
|
||||
entity.setGroupId(groupId);
|
||||
return entity;
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("写:店铺与分组的写入口一律不收 company_id——归属不从界面注入(§6.2,未批的界面暴露)")
|
||||
void writeEntryPointsCarryNoCompanyId() {
|
||||
String text = SourceScan.sourceText("ShopManageController.java");
|
||||
// 必须逐方法体判:page 这个读入口这轮就要加 company_id,全文 doesNotContain 会被自己弄红。
|
||||
for (String writer : List.of("create", "update", "delete", "createGroup", "updateGroup", "deleteGroup")) {
|
||||
assertThat(SourceScan.methodBody(text, writer))
|
||||
.as("写入口「" + writer + "」一旦出现 company_id,等于把公司维度端回界面(未批)")
|
||||
.doesNotContain("company_id")
|
||||
.doesNotContain("companyId");
|
||||
}
|
||||
assertThat(SourceScan.methodBody(text, "page")).contains("company_id");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,144 @@
|
||||
package com.nanri.aiimage.testutil;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
/** 源码扫描式护栏的取文助手。<b>路径解析照抄 {@code common/security/InternalTokenSingleOutletTest} 的
|
||||
* moduleRoot()/mainSources() 两支</b>——surefire 的 cwd 是模块目录,从仓库根或 IDE 跑时要退到 backend-java/,
|
||||
* 定位不到必须 fail 而不是静默跳过(静默跳过 = 整支护栏恒绿)。 */
|
||||
public final class SourceScan {
|
||||
|
||||
private SourceScan() {
|
||||
}
|
||||
|
||||
/** 按文件名(不含目录)取 {@code src/main/java} 下那份源码的<b>全文字符串</b>。
|
||||
* ⚠️ 返回 String,与 InternalTokenSingleOutletTest 里那个返回 Path 的私有 {@code sourceOf} 不是一回事,
|
||||
* 别指望复用它的——那个是 private。 */
|
||||
public static String sourceText(String fileName) {
|
||||
return mainSources().stream()
|
||||
.filter(p -> p.getFileName().toString().equals(fileName))
|
||||
.findFirst()
|
||||
.map(SourceScan::read)
|
||||
.orElseThrow(() -> new IllegalStateException(
|
||||
"src/main/java 下找不到 " + fileName + " —— 文件改名/挪目录了,护栏要红在这里"));
|
||||
}
|
||||
|
||||
/** 大括号配平切出「某个方法」的源码:<b>从它的签名行往前一直含到注解</b>,到方法收尾的 `}` 为止。
|
||||
*
|
||||
* <p>两条它必须自己防住的坑,都写在用例里过:</p>
|
||||
* <ul>
|
||||
* <li><b>名字必须是完整词</b>:{@code delete} 是 {@code deleteGroup} 的前缀。用 {@code indexOf(name)}
|
||||
* 会先撞上那个更长的方法 ⇒ "切出来的是隔壁",而断言仍然绿。所以下面用 {@code (?<![A-Za-z0-9_])} 卡左边界,
|
||||
* 并且要求紧跟 {@code (}(构造器/局部变量名同前缀也不算方法)。</li>
|
||||
* <li><b>找不到必须抛</b>,不许返回空串:返回 "" 的话 {@code doesNotContain("company_id")} 恒真,
|
||||
* 反向钉会因为方法被改名而悄悄失效(memory「字符串断言必须排他、解析断言必须可匹配」)。
|
||||
* 配套要求:每个用它的反向钉都要带一条"该做的确实做了"的取样自检。</li>
|
||||
* </ul>
|
||||
*/
|
||||
public static String methodBody(String source, String methodName) {
|
||||
var matcher = java.util.regex.Pattern
|
||||
.compile("(?<![A-Za-z0-9_])" + java.util.regex.Pattern.quote(methodName) + "\\s*\\(")
|
||||
.matcher(source);
|
||||
while (matcher.find()) {
|
||||
int open = matcher.end() - 1;
|
||||
int signatureStart = findSignatureStart(source, matcher.start());
|
||||
int bodyEnd = matchBraces(source, nextBrace(source, open));
|
||||
if (bodyEnd < 0) {
|
||||
continue;
|
||||
}
|
||||
return source.substring(signatureStart, bodyEnd + 1);
|
||||
}
|
||||
throw new AssertionError("源码里没有方法「" + methodName + "」——它被改名或删掉了。"
|
||||
+ "反向钉宁可红在这里,也不许因为切不到方法而恒绿。");
|
||||
}
|
||||
|
||||
/** 从签名的左括号往前退到上一条 `{`/`}`/`;` 之后,再退回到第一行注解的起始(注解属于这个方法,必须含进来)。 */
|
||||
private static int findSignatureStart(String source, int nameStart) {
|
||||
int boundary = 0;
|
||||
for (int i = nameStart; i-- > 0; ) {
|
||||
char c = source.charAt(i);
|
||||
if (c == '{' || c == '}' || c == ';') {
|
||||
boundary = i + 1;
|
||||
break;
|
||||
}
|
||||
}
|
||||
String head = source.substring(boundary, nameStart);
|
||||
int firstMeaningful = head.length();
|
||||
for (String raw : head.split("\n", -1)) {
|
||||
if (!raw.isBlank()) {
|
||||
firstMeaningful = head.indexOf(raw.stripLeading());
|
||||
break;
|
||||
}
|
||||
}
|
||||
return boundary + firstMeaningful;
|
||||
}
|
||||
|
||||
private static int nextBrace(String source, int from) {
|
||||
for (int i = from; i < source.length(); i++) {
|
||||
if (source.charAt(i) == '{') {
|
||||
return i;
|
||||
}
|
||||
if (source.charAt(i) == ';') {
|
||||
return -1; // 抽象方法/接口声明,不是我们要切的东西
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
/** 朴素配平:源码里的 `{` 与 `}` 若出现在字符串字面量里会算错。本仓库 controller 没有这种写法,
|
||||
* 但这条限制必须写在脸上——将来有人往方法体里塞一段带花括号的字符串,这个助手会悄悄切短。 */
|
||||
private static int matchBraces(String source, int open) {
|
||||
if (open < 0) {
|
||||
return -1;
|
||||
}
|
||||
int depth = 0;
|
||||
for (int i = open; i < source.length(); i++) {
|
||||
char c = source.charAt(i);
|
||||
if (c == '{') {
|
||||
depth++;
|
||||
} else if (c == '}') {
|
||||
if (--depth == 0) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
private static List<Path> mainSources() {
|
||||
Path root = moduleRoot().resolve("src/main/java");
|
||||
try (Stream<Path> walk = Files.walk(root)) {
|
||||
return walk.filter(Files::isRegularFile)
|
||||
.filter(p -> p.getFileName().toString().endsWith(".java"))
|
||||
.collect(Collectors.toList());
|
||||
} catch (IOException e) {
|
||||
// 定位不到必须抛,不许静默返回空表:返回空 ⇒ sourceText 那支护栏扫不到任何文件而恒绿。
|
||||
throw new IllegalStateException("遍历 " + root + " 失败: " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
private static Path moduleRoot() {
|
||||
Path here = Path.of("").toAbsolutePath();
|
||||
if (Files.isDirectory(here.resolve("src/main/java"))) {
|
||||
return here;
|
||||
}
|
||||
Path nested = here.resolve("backend-java");
|
||||
if (Files.isDirectory(nested.resolve("src/main/java"))) {
|
||||
return nested;
|
||||
}
|
||||
throw new IllegalStateException("无法定位 backend-java 模块目录(cwd=" + here + ")");
|
||||
}
|
||||
|
||||
private static String read(Path file) {
|
||||
try {
|
||||
return Files.readString(file, StandardCharsets.UTF_8);
|
||||
} catch (IOException e) {
|
||||
throw new IllegalStateException("读取失败: " + file, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user