修复回归安全问题并补充验证

This commit is contained in:
xiaowang
2026-06-05 16:10:58 +08:00
parent 784bb0a965
commit 74f8fa5f4e
46 changed files with 917 additions and 311 deletions
@@ -4,36 +4,38 @@ import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
/**
* JWT 配置。
*/
import java.nio.charset.StandardCharsets;
@Data
@Configuration
@ConfigurationProperties(prefix = "yuminail.security.jwt")
public class JwtProperties {
/**
* HS512 密钥,生产环境请通过 Nacos 覆盖。
*/
private String secret = "yuminail-secret-key-for-jwt-token-generation-2026-must-be-at-least-512-bits-long-for-hs512-algorithm-security-requirements";
public static final String DEVELOPMENT_PLACEHOLDER_SECRET = "__CONFIGURE_YUMINAIL_JWT_SECRET_OUTSIDE_REPOSITORY__";
private static final int HS512_MIN_SECRET_BYTES = 64;
/**
* Token 发行者。
* HS512 signing key. Production and shared environments must provide it through Nacos or environment variables.
*/
private String secret = DEVELOPMENT_PLACEHOLDER_SECRET;
private String issuer = "yuminail";
/**
* AccessToken 有效期,单位秒。
*/
private long accessTokenExpirationSeconds = 2 * 60 * 60;
/**
* RefreshToken 有效期,单位秒。
*/
private long refreshTokenExpirationSeconds = 7 * 24 * 60 * 60;
/**
* 时钟偏移容忍,单位秒。
*/
private long clockSkewSeconds = 30;
public void requireValidSecret() {
if (secret == null || secret.isBlank()) {
throw new IllegalStateException("JWT 密钥不能为空,请通过外部配置提供 yuminail.security.jwt.secret");
}
if (DEVELOPMENT_PLACEHOLDER_SECRET.equals(secret)) {
throw new IllegalStateException("JWT 密钥仍为仓库占位值,请通过外部配置覆盖后再启动服务");
}
if (secret.getBytes(StandardCharsets.UTF_8).length < HS512_MIN_SECRET_BYTES) {
throw new IllegalStateException("JWT 密钥长度不足,HS512 至少需要 64 字节");
}
}
}
@@ -11,12 +11,22 @@ import java.time.LocalTime;
@Mapper
public interface ArtistScheduleMapper extends BaseMapper<ArtistScheduleDO> {
@Select("SELECT * FROM t_artist_schedule WHERE shop_id = #{shopId} AND artist_id = #{artistId} " +
"AND work_date = #{workDate} AND start_time <= #{startTime} AND end_time >= #{endTime} " +
"AND is_delete = 0 ORDER BY CASE WHEN status = 1 THEN 0 ELSE 1 END, start_time ASC LIMIT 1 FOR UPDATE")
"AND is_delete = 0 ORDER BY CASE WHEN status = 1 THEN 0 ELSE 1 END, start_time ASC LIMIT 1")
ArtistScheduleDO selectCoveringSchedule(@Param("shopId") Long shopId,
@Param("artistId") Long artistId,
@Param("workDate") LocalDate workDate,
@Param("startTime") LocalTime startTime,
@Param("endTime") LocalTime endTime);
@Select("SELECT * FROM t_artist_schedule WHERE shop_id = #{shopId} AND artist_id = #{artistId} " +
"AND work_date = #{workDate} AND start_time <= #{startTime} AND end_time >= #{endTime} " +
"AND is_delete = 0 ORDER BY CASE WHEN status = 1 THEN 0 ELSE 1 END, start_time ASC LIMIT 1 FOR UPDATE")
ArtistScheduleDO selectCoveringScheduleForUpdate(@Param("shopId") Long shopId,
@Param("artistId") Long artistId,
@Param("workDate") LocalDate workDate,
@Param("startTime") LocalTime startTime,
@Param("endTime") LocalTime endTime);
}
@@ -1,12 +1,17 @@
package com.xiaowang.yuminailcore.modules.auth.controller.front;
import com.xiaowang.yuminailcore.annotation.RequirePermission;
import com.xiaowang.yuminailcore.common.Result;
import com.xiaowang.yuminailcore.modules.auth.dto.LoginIdentityDTO;
import com.xiaowang.yuminailcore.modules.auth.vo.LoginIdentityVO;
import com.xiaowang.yuminailcore.modules.auth.service.LoginIdentityService;
import com.xiaowang.yuminailcore.modules.security.support.AdminScopeHelper;
import com.xiaowang.yuminailcore.modules.shop.support.UserShopBindingSupport;
import com.xiaowang.yuminailcore.modules.user.entity.UserDO;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
/**
@@ -24,6 +29,8 @@ public class LoginIdentityController {
* Variable `loginIdentityService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/
private final LoginIdentityService loginIdentityService;
private final AdminScopeHelper adminScopeHelper;
private final UserShopBindingSupport userShopBindingSupport;
/**
* 创建登录标识
@@ -32,7 +39,10 @@ public class LoginIdentityController {
* @return 登录标识ID
*/
@PostMapping("/create")
public Result<Long> createLoginIdentity(@RequestBody LoginIdentityDTO loginIdentityDTO) {
@RequirePermission("user:create")
public Result<Long> createLoginIdentity(HttpServletRequest request, @RequestBody LoginIdentityDTO loginIdentityDTO) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
ensureTargetUserAccessible(currentUser, loginIdentityDTO.getUserId(), "无权为其他店铺用户创建登录标识");
Long id = loginIdentityService.createLoginIdentity(loginIdentityDTO);
return Result.success(id);
}
@@ -45,7 +55,14 @@ public class LoginIdentityController {
* @return 是否更新成功
*/
@PutMapping("/update/{id}")
public Result<Boolean> updateLoginIdentity(@PathVariable Long id, @RequestBody LoginIdentityDTO loginIdentityDTO) {
@RequirePermission("user:edit")
public Result<Boolean> updateLoginIdentity(HttpServletRequest request, @PathVariable Long id, @RequestBody LoginIdentityDTO loginIdentityDTO) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
LoginIdentityVO existing = loginIdentityService.getLoginIdentityById(id);
if (existing != null) {
ensureTargetUserAccessible(currentUser, existing.getUserId(), "无权编辑其他店铺用户登录标识");
}
ensureTargetUserAccessible(currentUser, loginIdentityDTO.getUserId(), "无权将登录标识改到其他店铺用户");
boolean success = loginIdentityService.updateLoginIdentity(id, loginIdentityDTO);
return Result.success(success);
}
@@ -57,7 +74,13 @@ public class LoginIdentityController {
* @return 是否删除成功
*/
@DeleteMapping("/delete/{id}")
public Result<Boolean> deleteLoginIdentity(@PathVariable Long id) {
@RequirePermission("user:delete")
public Result<Boolean> deleteLoginIdentity(HttpServletRequest request, @PathVariable Long id) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
LoginIdentityVO existing = loginIdentityService.getLoginIdentityById(id);
if (existing != null) {
ensureTargetUserAccessible(currentUser, existing.getUserId(), "无权删除其他店铺用户登录标识");
}
boolean success = loginIdentityService.deleteLoginIdentity(id);
return Result.success(success);
}
@@ -69,8 +92,13 @@ public class LoginIdentityController {
* @return 登录标识VO
*/
@GetMapping("/get/{id}")
public Result<LoginIdentityVO> getLoginIdentityById(@PathVariable Long id) {
@RequirePermission("user:view")
public Result<LoginIdentityVO> getLoginIdentityById(HttpServletRequest request, @PathVariable Long id) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
LoginIdentityVO loginIdentityVO = loginIdentityService.getLoginIdentityById(id);
if (loginIdentityVO != null) {
ensureTargetUserAccessible(currentUser, loginIdentityVO.getUserId(), "无权查看其他店铺用户登录标识");
}
return Result.success(loginIdentityVO);
}
@@ -80,8 +108,12 @@ public class LoginIdentityController {
* @return 登录标识VO列表
*/
@GetMapping("/list/all")
public Result<List<LoginIdentityVO>> listAllLoginIdentities() {
List<LoginIdentityVO> loginIdentityVOs = loginIdentityService.listAllLoginIdentities();
@RequirePermission("user:view")
public Result<List<LoginIdentityVO>> listAllLoginIdentities(HttpServletRequest request) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
List<LoginIdentityVO> loginIdentityVOs = adminScopeHelper.isPlatformAdmin(currentUser)
? loginIdentityService.listAllLoginIdentities()
: loginIdentityService.listLoginIdentitiesByUserIds(scopedUserIds(currentUser));
return Result.success(loginIdentityVOs);
}
@@ -92,7 +124,10 @@ public class LoginIdentityController {
* @return 登录标识VO列表
*/
@GetMapping("/list/user/{userId}")
public Result<List<LoginIdentityVO>> listLoginIdentitiesByUserId(@PathVariable Long userId) {
@RequirePermission("user:view")
public Result<List<LoginIdentityVO>> listLoginIdentitiesByUserId(HttpServletRequest request, @PathVariable Long userId) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
ensureTargetUserAccessible(currentUser, userId, "无权查看其他店铺用户登录标识");
List<LoginIdentityVO> loginIdentityVOs = loginIdentityService.listLoginIdentitiesByUserId(userId);
return Result.success(loginIdentityVOs);
}
@@ -104,8 +139,21 @@ public class LoginIdentityController {
* @return 登录标识VO列表
*/
@GetMapping("/list/loginMethod/{loginMethod}")
public Result<List<LoginIdentityVO>> listLoginIdentitiesByLoginMethod(@PathVariable String loginMethod) {
List<LoginIdentityVO> loginIdentityVOs = loginIdentityService.listLoginIdentitiesByLoginMethod(loginMethod);
@RequirePermission("user:view")
public Result<List<LoginIdentityVO>> listLoginIdentitiesByLoginMethod(HttpServletRequest request, @PathVariable String loginMethod) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
List<LoginIdentityVO> loginIdentityVOs = adminScopeHelper.isPlatformAdmin(currentUser)
? loginIdentityService.listLoginIdentitiesByLoginMethod(loginMethod)
: loginIdentityService.listLoginIdentitiesByLoginMethodAndUserIds(loginMethod, scopedUserIds(currentUser));
return Result.success(loginIdentityVOs);
}
private List<Long> scopedUserIds(UserDO currentUser) {
Long managedShopId = adminScopeHelper.getManagedShopId(currentUser);
return userShopBindingSupport.listUserIdsByShopId(managedShopId, true);
}
private void ensureTargetUserAccessible(UserDO currentUser, Long targetUserId, String message) {
adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, targetUserId, message);
}
}
@@ -5,6 +5,7 @@ import com.xiaowang.yuminailcore.modules.auth.entity.LoginIdentityDO;
import com.xiaowang.yuminailcore.modules.auth.dto.LoginIdentityDTO;
import com.xiaowang.yuminailcore.modules.auth.vo.LoginIdentityVO;
import java.util.Collection;
import java.util.List;
/**
@@ -56,6 +57,8 @@ public interface LoginIdentityService extends IService<LoginIdentityDO> {
*/
List<LoginIdentityVO> listAllLoginIdentities();
List<LoginIdentityVO> listLoginIdentitiesByUserIds(Collection<Long> userIds);
/**
* 根据用户ID查询登录标识
*
@@ -71,4 +74,6 @@ public interface LoginIdentityService extends IService<LoginIdentityDO> {
* @return 登录标识VO列表
*/
List<LoginIdentityVO> listLoginIdentitiesByLoginMethod(String loginMethod);
List<LoginIdentityVO> listLoginIdentitiesByLoginMethodAndUserIds(String loginMethod, Collection<Long> userIds);
}
@@ -10,6 +10,7 @@ import com.xiaowang.yuminailcore.modules.auth.vo.LoginIdentityVO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
@@ -113,6 +114,21 @@ public class LoginIdentityServiceImpl extends ServiceImpl<LoginIdentityMapper, L
.collect(Collectors.toList());
}
@Override
public List<LoginIdentityVO> listLoginIdentitiesByUserIds(Collection<Long> userIds) {
List<Long> scopedUserIds = normalizeUserIds(userIds);
if (scopedUserIds.isEmpty()) {
return List.of();
}
List<LoginIdentityDO> loginIdentityDOs = loginIdentityMapper.selectList(
Wrappers.lambdaQuery(LoginIdentityDO.class)
.in(LoginIdentityDO::getUserId, scopedUserIds)
);
return loginIdentityDOs.stream()
.map(this::convertToVO)
.collect(Collectors.toList());
}
@Override
/**
* List records for the current query or current user scope.
@@ -147,6 +163,32 @@ public class LoginIdentityServiceImpl extends ServiceImpl<LoginIdentityMapper, L
.collect(Collectors.toList());
}
@Override
public List<LoginIdentityVO> listLoginIdentitiesByLoginMethodAndUserIds(String loginMethod, Collection<Long> userIds) {
List<Long> scopedUserIds = normalizeUserIds(userIds);
if (scopedUserIds.isEmpty()) {
return List.of();
}
List<LoginIdentityDO> loginIdentityDOs = loginIdentityMapper.selectList(
Wrappers.lambdaQuery(LoginIdentityDO.class)
.eq(LoginIdentityDO::getLoginMethod, loginMethod)
.in(LoginIdentityDO::getUserId, scopedUserIds)
);
return loginIdentityDOs.stream()
.map(this::convertToVO)
.collect(Collectors.toList());
}
private List<Long> normalizeUserIds(Collection<Long> userIds) {
if (userIds == null || userIds.isEmpty()) {
return List.of();
}
return userIds.stream()
.filter(id -> id != null && id > 0)
.distinct()
.collect(Collectors.toList());
}
/**
* 将 DO 转换为 VO
*
@@ -1,12 +1,15 @@
package com.xiaowang.yuminailcore.modules.marketing.controller.front;
import com.xiaowang.yuminailcore.annotation.RequirePermission;
import com.xiaowang.yuminailcore.common.Result;
import com.xiaowang.yuminailcore.modules.marketing.dto.VipBenefitDTO;
import com.xiaowang.yuminailcore.modules.marketing.vo.VipBenefitVO;
import com.xiaowang.yuminailcore.modules.marketing.service.VipBenefitService;
import com.xiaowang.yuminailcore.modules.security.support.AdminScopeHelper;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
/**
@@ -24,6 +27,7 @@ public class VipBenefitController {
* Variable `vipBenefitService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/
private final VipBenefitService vipBenefitService;
private final AdminScopeHelper adminScopeHelper;
/**
* 创建VIP权益
@@ -32,7 +36,9 @@ public class VipBenefitController {
* @return VIP权益ID
*/
@PostMapping("/create")
public Result<Long> createVipBenefit(@RequestBody VipBenefitDTO vipBenefitDTO) {
@RequirePermission("user:vip:manage")
public Result<Long> createVipBenefit(HttpServletRequest request, @RequestBody VipBenefitDTO vipBenefitDTO) {
requirePlatformAdmin(request);
Long id = vipBenefitService.createVipBenefit(vipBenefitDTO);
return Result.success(id);
}
@@ -45,7 +51,9 @@ public class VipBenefitController {
* @return 是否更新成功
*/
@PutMapping("/update/{id}")
public Result<Boolean> updateVipBenefit(@PathVariable Long id, @RequestBody VipBenefitDTO vipBenefitDTO) {
@RequirePermission("user:vip:manage")
public Result<Boolean> updateVipBenefit(HttpServletRequest request, @PathVariable Long id, @RequestBody VipBenefitDTO vipBenefitDTO) {
requirePlatformAdmin(request);
boolean success = vipBenefitService.updateVipBenefit(id, vipBenefitDTO);
return Result.success(success);
}
@@ -57,7 +65,9 @@ public class VipBenefitController {
* @return 是否删除成功
*/
@DeleteMapping("/delete/{id}")
public Result<Boolean> deleteVipBenefit(@PathVariable Long id) {
@RequirePermission("user:vip:manage")
public Result<Boolean> deleteVipBenefit(HttpServletRequest request, @PathVariable Long id) {
requirePlatformAdmin(request);
boolean success = vipBenefitService.deleteVipBenefit(id);
return Result.success(success);
}
@@ -69,7 +79,9 @@ public class VipBenefitController {
* @return VIP权益VO
*/
@GetMapping("/get/{id}")
public Result<VipBenefitVO> getVipBenefitById(@PathVariable Long id) {
@RequirePermission("user:vip:manage")
public Result<VipBenefitVO> getVipBenefitById(HttpServletRequest request, @PathVariable Long id) {
requirePlatformAdmin(request);
VipBenefitVO vipBenefitVO = vipBenefitService.getVipBenefitById(id);
return Result.success(vipBenefitVO);
}
@@ -80,7 +92,9 @@ public class VipBenefitController {
* @return VIP权益VO列表
*/
@GetMapping("/list/all")
public Result<List<VipBenefitVO>> listAllVipBenefits() {
@RequirePermission("user:vip:manage")
public Result<List<VipBenefitVO>> listAllVipBenefits(HttpServletRequest request) {
requirePlatformAdmin(request);
List<VipBenefitVO> vipBenefitVOs = vipBenefitService.listAllVipBenefits();
return Result.success(vipBenefitVOs);
}
@@ -92,8 +106,17 @@ public class VipBenefitController {
* @return VIP权益VO列表
*/
@GetMapping("/list/requiredVipLevel/{requiredVipLevel}")
public Result<List<VipBenefitVO>> listVipBenefitsByRequiredVipLevel(@PathVariable String requiredVipLevel) {
@RequirePermission("user:vip:manage")
public Result<List<VipBenefitVO>> listVipBenefitsByRequiredVipLevel(HttpServletRequest request, @PathVariable String requiredVipLevel) {
requirePlatformAdmin(request);
List<VipBenefitVO> vipBenefitVOs = vipBenefitService.listVipBenefitsByRequiredVipLevel(requiredVipLevel);
return Result.success(vipBenefitVOs);
}
private void requirePlatformAdmin(HttpServletRequest request) {
adminScopeHelper.requirePlatformAdmin(
adminScopeHelper.getCurrentUser(request),
"只有平台管理员可以维护全局VIP权益配置"
);
}
}
@@ -1,12 +1,17 @@
package com.xiaowang.yuminailcore.modules.marketing.controller.front;
import com.xiaowang.yuminailcore.annotation.RequirePermission;
import com.xiaowang.yuminailcore.common.Result;
import com.xiaowang.yuminailcore.modules.marketing.dto.VipInfoDTO;
import com.xiaowang.yuminailcore.modules.marketing.vo.VipInfoVO;
import com.xiaowang.yuminailcore.modules.marketing.service.VipInfoService;
import com.xiaowang.yuminailcore.modules.security.support.AdminScopeHelper;
import com.xiaowang.yuminailcore.modules.shop.support.UserShopBindingSupport;
import com.xiaowang.yuminailcore.modules.user.entity.UserDO;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
/**
@@ -24,6 +29,8 @@ public class VipInfoController {
* Variable `vipInfoService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/
private final VipInfoService vipInfoService;
private final AdminScopeHelper adminScopeHelper;
private final UserShopBindingSupport userShopBindingSupport;
/**
* 创建VIP信息
@@ -32,7 +39,10 @@ public class VipInfoController {
* @return VIP信息ID
*/
@PostMapping("/create")
public Result<Long> createVipInfo(@RequestBody VipInfoDTO vipInfoDTO) {
@RequirePermission("user:vip:manage")
public Result<Long> createVipInfo(HttpServletRequest request, @RequestBody VipInfoDTO vipInfoDTO) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
ensureTargetUserAccessible(currentUser, vipInfoDTO.getUserId(), "无权为其他店铺用户创建VIP信息");
Long id = vipInfoService.createVipInfo(vipInfoDTO);
return Result.success(id);
}
@@ -45,7 +55,14 @@ public class VipInfoController {
* @return 是否更新成功
*/
@PutMapping("/update/{id}")
public Result<Boolean> updateVipInfo(@PathVariable Long id, @RequestBody VipInfoDTO vipInfoDTO) {
@RequirePermission("user:vip:manage")
public Result<Boolean> updateVipInfo(HttpServletRequest request, @PathVariable Long id, @RequestBody VipInfoDTO vipInfoDTO) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
VipInfoVO existing = vipInfoService.getVipInfoById(id);
if (existing != null) {
ensureTargetUserAccessible(currentUser, existing.getUserId(), "无权编辑其他店铺用户VIP信息");
}
ensureTargetUserAccessible(currentUser, vipInfoDTO.getUserId(), "无权将VIP信息改到其他店铺用户");
boolean success = vipInfoService.updateVipInfo(id, vipInfoDTO);
return Result.success(success);
}
@@ -57,7 +74,13 @@ public class VipInfoController {
* @return 是否删除成功
*/
@DeleteMapping("/delete/{id}")
public Result<Boolean> deleteVipInfo(@PathVariable Long id) {
@RequirePermission("user:vip:manage")
public Result<Boolean> deleteVipInfo(HttpServletRequest request, @PathVariable Long id) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
VipInfoVO existing = vipInfoService.getVipInfoById(id);
if (existing != null) {
ensureTargetUserAccessible(currentUser, existing.getUserId(), "无权删除其他店铺用户VIP信息");
}
boolean success = vipInfoService.deleteVipInfo(id);
return Result.success(success);
}
@@ -69,8 +92,13 @@ public class VipInfoController {
* @return VIP信息VO
*/
@GetMapping("/get/{id}")
public Result<VipInfoVO> getVipInfoById(@PathVariable Long id) {
@RequirePermission("user:vip:manage")
public Result<VipInfoVO> getVipInfoById(HttpServletRequest request, @PathVariable Long id) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
VipInfoVO vipInfoVO = vipInfoService.getVipInfoById(id);
if (vipInfoVO != null) {
ensureTargetUserAccessible(currentUser, vipInfoVO.getUserId(), "无权查看其他店铺用户VIP信息");
}
return Result.success(vipInfoVO);
}
@@ -80,8 +108,12 @@ public class VipInfoController {
* @return VIP信息VO列表
*/
@GetMapping("/list/all")
public Result<List<VipInfoVO>> listAllVipInfos() {
List<VipInfoVO> vipInfoVOs = vipInfoService.listAllVipInfos();
@RequirePermission("user:vip:manage")
public Result<List<VipInfoVO>> listAllVipInfos(HttpServletRequest request) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
List<VipInfoVO> vipInfoVOs = adminScopeHelper.isPlatformAdmin(currentUser)
? vipInfoService.listAllVipInfos()
: vipInfoService.listVipInfosByUserIds(scopedUserIds(currentUser));
return Result.success(vipInfoVOs);
}
@@ -92,8 +124,21 @@ public class VipInfoController {
* @return VIP信息VO列表
*/
@GetMapping("/list/vipLevel/{vipLevel}")
public Result<List<VipInfoVO>> listVipInfosByVipLevel(@PathVariable String vipLevel) {
List<VipInfoVO> vipInfoVOs = vipInfoService.listVipInfosByVipLevel(vipLevel);
@RequirePermission("user:vip:manage")
public Result<List<VipInfoVO>> listVipInfosByVipLevel(HttpServletRequest request, @PathVariable String vipLevel) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
List<VipInfoVO> vipInfoVOs = adminScopeHelper.isPlatformAdmin(currentUser)
? vipInfoService.listVipInfosByVipLevel(vipLevel)
: vipInfoService.listVipInfosByVipLevelAndUserIds(vipLevel, scopedUserIds(currentUser));
return Result.success(vipInfoVOs);
}
private List<Long> scopedUserIds(UserDO currentUser) {
Long managedShopId = adminScopeHelper.getManagedShopId(currentUser);
return userShopBindingSupport.listUserIdsByShopId(managedShopId, true);
}
private void ensureTargetUserAccessible(UserDO currentUser, Long targetUserId, String message) {
adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, targetUserId, message);
}
}
@@ -5,6 +5,7 @@ import com.xiaowang.yuminailcore.modules.marketing.entity.VipInfoDO;
import com.xiaowang.yuminailcore.modules.marketing.dto.VipInfoDTO;
import com.xiaowang.yuminailcore.modules.marketing.vo.VipInfoVO;
import java.util.Collection;
import java.util.List;
/**
@@ -56,6 +57,8 @@ public interface VipInfoService extends IService<VipInfoDO> {
*/
List<VipInfoVO> listAllVipInfos();
List<VipInfoVO> listVipInfosByUserIds(Collection<Long> userIds);
/**
* 根据VIP等级查询VIP信息
*
@@ -63,4 +66,6 @@ public interface VipInfoService extends IService<VipInfoDO> {
* @return VIP信息VO列表
*/
List<VipInfoVO> listVipInfosByVipLevel(String vipLevel);
List<VipInfoVO> listVipInfosByVipLevelAndUserIds(String vipLevel, Collection<Long> userIds);
}
@@ -10,6 +10,7 @@ import com.xiaowang.yuminailcore.modules.marketing.vo.VipInfoVO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
@@ -117,6 +118,21 @@ public class VipInfoServiceImpl extends ServiceImpl<VipInfoMapper, VipInfoDO> im
.collect(Collectors.toList());
}
@Override
public List<VipInfoVO> listVipInfosByUserIds(Collection<Long> userIds) {
List<Long> scopedUserIds = normalizeUserIds(userIds);
if (scopedUserIds.isEmpty()) {
return List.of();
}
List<VipInfoDO> vipInfoDOs = vipInfoMapper.selectList(
Wrappers.lambdaQuery(VipInfoDO.class)
.in(VipInfoDO::getUserId, scopedUserIds)
);
return vipInfoDOs.stream()
.map(this::convertToVO)
.collect(Collectors.toList());
}
@Override
/**
* List records for the current query or current user scope.
@@ -134,6 +150,32 @@ public class VipInfoServiceImpl extends ServiceImpl<VipInfoMapper, VipInfoDO> im
.collect(Collectors.toList());
}
@Override
public List<VipInfoVO> listVipInfosByVipLevelAndUserIds(String vipLevel, Collection<Long> userIds) {
List<Long> scopedUserIds = normalizeUserIds(userIds);
if (scopedUserIds.isEmpty()) {
return List.of();
}
List<VipInfoDO> vipInfoDOs = vipInfoMapper.selectList(
Wrappers.lambdaQuery(VipInfoDO.class)
.eq(VipInfoDO::getVipLevel, vipLevel)
.in(VipInfoDO::getUserId, scopedUserIds)
);
return vipInfoDOs.stream()
.map(this::convertToVO)
.collect(Collectors.toList());
}
private List<Long> normalizeUserIds(Collection<Long> userIds) {
if (userIds == null || userIds.isEmpty()) {
return List.of();
}
return userIds.stream()
.filter(id -> id != null && id > 0)
.distinct()
.collect(Collectors.toList());
}
/**
* 将 DO 转换为 VO
*
@@ -24,9 +24,4 @@ public class PaymentController {
return Result.success(paymentService.prepareOrderPayment(userId, orderId));
}
@PostMapping("/order/{orderId}/mock-success")
public Result<PaymentOrderVO> mockSuccess(HttpServletRequest request, @PathVariable Long orderId) {
Long userId = (Long) request.getAttribute("userId");
return Result.success(paymentService.manualConfirmOrderPaid(userId, orderId, "mock-success"));
}
}
@@ -1,9 +1,9 @@
package com.xiaowang.yuminailcore.modules.payment.service.impl;
import com.xiaowang.yuminailcore.modules.order.entity.OrderDO;
import com.xiaowang.yuminailcore.modules.order.mapper.OrderMapper;
import com.xiaowang.yuminailcore.modules.payment.entity.PaymentOrderDO;
import com.xiaowang.yuminailcore.modules.payment.entity.RefundOrderDO;
import com.xiaowang.yuminailcore.modules.order.mapper.OrderMapper;
import com.xiaowang.yuminailcore.modules.payment.mapper.PaymentOrderMapper;
import com.xiaowang.yuminailcore.modules.payment.mapper.RefundOrderMapper;
import com.xiaowang.yuminailcore.modules.payment.service.PaymentService;
@@ -93,14 +93,14 @@ public class PaymentServiceImpl implements PaymentService {
public RefundOrderVO manualRefundOrder(Long operatorId, Long orderId, Long afterSaleId, String remark) {
OrderDO order = orderMapper.selectById(orderId);
if (order == null || Integer.valueOf(1).equals(order.getIsDelete())) {
throw new RuntimeException("璁㈠崟涓嶅瓨鍦?");
throw new RuntimeException("订单不存在");
}
if (!STATUS_PAID.equals(order.getPaymentStatus())) {
throw new RuntimeException("鏈敮浠樿鍗曚笉鍏佽閫€娆?");
throw new RuntimeException("未支付订单不允许退款");
}
PaymentOrderDO payment = paymentOrderMapper.selectLatestByOrderId(orderId);
if (payment == null || !STATUS_PAID.equals(payment.getStatus())) {
throw new RuntimeException("鏈壘鍒板凡鏀粯鏀粯鍗?");
throw new RuntimeException("未找到已支付的支付单");
}
RefundOrderDO refund = new RefundOrderDO();
refund.setRefundNo("RF" + System.currentTimeMillis() + orderId);
@@ -132,7 +132,7 @@ public class PaymentServiceImpl implements PaymentService {
throw new RuntimeException("无权支付该订单");
}
if (Integer.valueOf(0).equals(order.getStatus())) {
throw new RuntimeException("询价预约确认价格前暂不能支付");
throw new RuntimeException("请先确认预约报价后再支付");
}
if (STATUS_PAID.equals(order.getPaymentStatus())) {
throw new RuntimeException("订单已支付");
@@ -11,20 +11,6 @@ import java.time.LocalDateTime;
@Mapper
public interface AppointmentReservationMapper extends BaseMapper<AppointmentReservationDO> {
@Select("SELECT COUNT(*) FROM t_appointment_reservation WHERE artist_id = #{artistId} " +
"AND status IN ('LOCKED','CONFIRMED') AND is_delete = 0 " +
"AND appointment_start_time < #{endTime} AND appointment_end_time > #{startTime} FOR UPDATE")
int countOverlappingActiveForUpdate(@Param("artistId") Long artistId,
@Param("startTime") LocalDateTime startTime,
@Param("endTime") LocalDateTime endTime);
@Select("SELECT COUNT(*) FROM t_appointment_reservation WHERE artist_id = #{artistId} " +
"AND order_item_id <> #{orderItemId} AND status IN ('LOCKED','CONFIRMED') AND is_delete = 0 " +
"AND appointment_start_time < #{endTime} AND appointment_end_time > #{startTime} FOR UPDATE")
int countOverlappingActiveForUpdateExcludingOrderItem(@Param("artistId") Long artistId,
@Param("orderItemId") Long orderItemId,
@Param("startTime") LocalDateTime startTime,
@Param("endTime") LocalDateTime endTime);
@Select("SELECT COUNT(*) FROM t_appointment_reservation WHERE artist_id = #{artistId} " +
"AND status IN ('LOCKED','CONFIRMED') AND is_delete = 0 " +
@@ -33,6 +19,14 @@ public interface AppointmentReservationMapper extends BaseMapper<AppointmentRese
@Param("startTime") LocalDateTime startTime,
@Param("endTime") LocalDateTime endTime);
@Select("SELECT COUNT(*) FROM t_appointment_reservation WHERE artist_id = #{artistId} " +
"AND order_item_id <> #{orderItemId} AND status IN ('LOCKED','CONFIRMED') AND is_delete = 0 " +
"AND appointment_start_time < #{endTime} AND appointment_end_time > #{startTime}")
int countOverlappingActiveExcludingOrderItem(@Param("artistId") Long artistId,
@Param("orderItemId") Long orderItemId,
@Param("startTime") LocalDateTime startTime,
@Param("endTime") LocalDateTime endTime);
@Update("UPDATE t_appointment_reservation SET status = #{status}, is_delete = 1, update_time = NOW() " +
"WHERE order_id = #{orderId} AND is_delete = 0")
int releaseByOrderId(@Param("orderId") Long orderId, @Param("status") String status);
@@ -1,9 +1,9 @@
package com.xiaowang.yuminailcore.modules.planning.service.impl;
import com.xiaowang.yuminailcore.modules.planning.entity.AppointmentReservationDO;
import com.xiaowang.yuminailcore.modules.artist.entity.ArtistScheduleDO;
import com.xiaowang.yuminailcore.modules.planning.mapper.AppointmentReservationMapper;
import com.xiaowang.yuminailcore.modules.artist.mapper.ArtistScheduleMapper;
import com.xiaowang.yuminailcore.modules.planning.entity.AppointmentReservationDO;
import com.xiaowang.yuminailcore.modules.planning.mapper.AppointmentReservationMapper;
import com.xiaowang.yuminailcore.modules.planning.service.AppointmentCapacityService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
@@ -18,8 +18,8 @@ public class AppointmentCapacityServiceImpl implements AppointmentCapacityServic
private static final int MIN_CAPACITY = 1;
private static final String STATUS_CONFIRMED = "CONFIRMED";
private static final String STATUS_RELEASED = "RELEASED";
private static final String UNAVAILABLE_MESSAGE = "涓嶅彲棰勭害";
private static final String FULL_MESSAGE = "褰撳墠缇庣敳甯堣鏃堕棿娈靛凡绾︽弧锛岃閲嶆柊閫夋嫨棰勭害鏃堕棿";
private static final String UNAVAILABLE_MESSAGE = "当前美甲师该时间段不可预约";
private static final String FULL_MESSAGE = "当前美甲师该时间段已约满,请重新选择预约时间";
private final AppointmentReservationMapper reservationMapper;
private final ArtistScheduleMapper scheduleMapper;
@@ -79,17 +79,17 @@ public class AppointmentCapacityServiceImpl implements AppointmentCapacityServic
private void assertCapacityAvailable(Long shopId, Long artistId, Long excludedOrderItemId,
LocalDateTime startTime, LocalDateTime endTime) {
int capacity = resolveCapacity(shopId, artistId, startTime, endTime);
int capacity = resolveCapacityWithScheduleLock(shopId, artistId, startTime, endTime);
int used = excludedOrderItemId == null
? reservationMapper.countOverlappingActiveForUpdate(artistId, startTime, endTime)
: reservationMapper.countOverlappingActiveForUpdateExcludingOrderItem(artistId, excludedOrderItemId, startTime, endTime);
? reservationMapper.countOverlappingActive(artistId, startTime, endTime)
: reservationMapper.countOverlappingActiveExcludingOrderItem(artistId, excludedOrderItemId, startTime, endTime);
if (used >= capacity) {
throw new RuntimeException(FULL_MESSAGE);
}
}
private int resolveCapacity(Long shopId, Long artistId, LocalDateTime startTime, LocalDateTime endTime) {
ArtistScheduleDO schedule = scheduleMapper.selectCoveringSchedule(
private int resolveCapacityWithScheduleLock(Long shopId, Long artistId, LocalDateTime startTime, LocalDateTime endTime) {
ArtistScheduleDO schedule = scheduleMapper.selectCoveringScheduleForUpdate(
shopId,
artistId,
startTime.toLocalDate(),
@@ -8,6 +8,7 @@ import io.jsonwebtoken.security.Keys;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.util.Date;
@@ -28,11 +29,17 @@ public class JwtUtil {
*/
private final JwtProperties jwtProperties;
@PostConstruct
void validateJwtSecret() {
jwtProperties.requireValidSecret();
}
/**
* Purpose: getKey supports JwtUtil.java by holding or executing the get key business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
private SecretKey getKey() {
jwtProperties.requireValidSecret();
return Keys.hmacShaKeyFor(jwtProperties.getSecret().getBytes(StandardCharsets.UTF_8));
}
@@ -18,9 +18,9 @@ spring:
# 是否启用服务注册
register-enabled: true
# Nacos认证用户名
username: xiaowang
username: ${NACOS_USERNAME:xiaowang}
# Nacos认证密码
password: 122503wcy....
password: ${NACOS_PASSWORD:}
config:
# Nacos配置中心集群地址
server-addr: home-nacos01:8848,home-nacos02:8848,home-nacos03:8848
@@ -35,9 +35,9 @@ spring:
# 是否启用配置中心
enabled: true
# Nacos认证用户名
username: xiaowang
username: ${NACOS_USERNAME:xiaowang}
# Nacos认证密码
password: 122503wcy....
password: ${NACOS_PASSWORD:}
# 共享配置文件列表
shared-configs:
- data-id: rabbit-mq.yaml
@@ -0,0 +1,28 @@
package com.xiaowang.yuminailcore.config;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
class JwtPropertiesTest {
@Test
void rejectsMissingJwtSecretBeforeTokenOperations() {
JwtProperties properties = new JwtProperties();
properties.setSecret("");
assertThatThrownBy(properties::requireValidSecret)
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("JWT 密钥");
}
@Test
void rejectsCommittedDevelopmentJwtSecretBeforeTokenOperations() {
JwtProperties properties = new JwtProperties();
properties.setSecret(JwtProperties.DEVELOPMENT_PLACEHOLDER_SECRET);
assertThatThrownBy(properties::requireValidSecret)
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("外部配置");
}
}
@@ -0,0 +1,21 @@
package com.xiaowang.yuminailcore.modules.payment.controller.front;
import org.junit.jupiter.api.Test;
import org.springframework.web.bind.annotation.PostMapping;
import java.util.Arrays;
import static org.assertj.core.api.Assertions.assertThat;
class PaymentControllerSecurityTest {
@Test
void frontPaymentControllerDoesNotExposeMockPaymentSuccessEndpoint() {
boolean hasMockSuccessRoute = Arrays.stream(PaymentController.class.getDeclaredMethods())
.flatMap(method -> Arrays.stream(method.getAnnotationsByType(PostMapping.class)))
.flatMap(mapping -> Arrays.stream(mapping.value()))
.anyMatch(path -> path.contains("mock-success"));
assertThat(hasMockSuccessRoute).isFalse();
}
}
@@ -1,9 +1,9 @@
package com.xiaowang.yuminailcore.modules.planning.service.impl;
import com.xiaowang.yuminailcore.modules.planning.entity.AppointmentReservationDO;
import com.xiaowang.yuminailcore.modules.artist.entity.ArtistScheduleDO;
import com.xiaowang.yuminailcore.modules.planning.mapper.AppointmentReservationMapper;
import com.xiaowang.yuminailcore.modules.artist.mapper.ArtistScheduleMapper;
import com.xiaowang.yuminailcore.modules.planning.entity.AppointmentReservationDO;
import com.xiaowang.yuminailcore.modules.planning.mapper.AppointmentReservationMapper;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
@@ -16,8 +16,8 @@ import java.time.LocalTime;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class AppointmentCapacityServiceImplTest {
@@ -36,24 +36,28 @@ class AppointmentCapacityServiceImplTest {
}
@Test
void reserveRejectsWhenConfiguredCapacityIsFull() {
void reserveLocksCoveringScheduleRowAndRejectsWhenConfiguredCapacityIsFull() {
LocalDateTime start = LocalDateTime.of(2026, 6, 1, 10, 0);
LocalDateTime end = start.plusHours(1);
when(scheduleMapper.selectCoveringSchedule(9L, 30L, start.toLocalDate(), start.toLocalTime(), end.toLocalTime()))
when(scheduleMapper.selectCoveringScheduleForUpdate(9L, 30L, start.toLocalDate(), start.toLocalTime(), end.toLocalTime()))
.thenReturn(schedule(2));
when(reservationMapper.countOverlappingActiveForUpdate(30L, start, end)).thenReturn(2);
when(reservationMapper.countOverlappingActive(30L, start, end)).thenReturn(2);
assertThatThrownBy(() -> service.reserveOrThrow(1L, 10L, 9L, 30L, "French", start, end))
.isInstanceOf(RuntimeException.class);
.isInstanceOf(RuntimeException.class)
.hasMessageContaining("已约满");
verify(scheduleMapper).selectCoveringScheduleForUpdate(9L, 30L, start.toLocalDate(), start.toLocalTime(), end.toLocalTime());
verify(reservationMapper, never()).insert(org.mockito.ArgumentMatchers.any(AppointmentReservationDO.class));
}
@Test
void reserveCreatesConfirmedReservationWhenCapacityRemains() {
LocalDateTime start = LocalDateTime.of(2026, 6, 1, 10, 0);
LocalDateTime end = start.plusHours(1);
when(scheduleMapper.selectCoveringSchedule(9L, 30L, start.toLocalDate(), start.toLocalTime(), end.toLocalTime()))
when(scheduleMapper.selectCoveringScheduleForUpdate(9L, 30L, start.toLocalDate(), start.toLocalTime(), end.toLocalTime()))
.thenReturn(schedule(2));
when(reservationMapper.countOverlappingActiveForUpdate(30L, start, end)).thenReturn(1);
when(reservationMapper.countOverlappingActive(30L, start, end)).thenReturn(1);
service.reserveOrThrow(1L, 10L, 9L, 30L, "French", start, end);
@@ -70,12 +74,12 @@ class AppointmentCapacityServiceImplTest {
void reserveRejectsWhenNoCoveringScheduleExists() {
LocalDateTime start = LocalDateTime.of(2026, 6, 2, 10, 0);
LocalDateTime end = start.plusHours(1);
when(scheduleMapper.selectCoveringSchedule(9L, 30L, start.toLocalDate(), start.toLocalTime(), end.toLocalTime()))
when(scheduleMapper.selectCoveringScheduleForUpdate(9L, 30L, start.toLocalDate(), start.toLocalTime(), end.toLocalTime()))
.thenReturn(null);
assertThatThrownBy(() -> service.reserveOrThrow(1L, 10L, 9L, 30L, "French", start, end))
.isInstanceOf(RuntimeException.class)
.hasMessageContaining("涓嶅彲棰勭害");
.hasMessageContaining("不可预约");
verify(reservationMapper, never()).insert(org.mockito.ArgumentMatchers.any(AppointmentReservationDO.class));
}
@@ -86,12 +90,12 @@ class AppointmentCapacityServiceImplTest {
LocalDateTime end = start.plusHours(1);
ArtistScheduleDO disabled = schedule(1);
disabled.setStatus(0);
when(scheduleMapper.selectCoveringSchedule(9L, 30L, start.toLocalDate(), start.toLocalTime(), end.toLocalTime()))
when(scheduleMapper.selectCoveringScheduleForUpdate(9L, 30L, start.toLocalDate(), start.toLocalTime(), end.toLocalTime()))
.thenReturn(disabled);
assertThatThrownBy(() -> service.reserveOrThrow(1L, 10L, 9L, 30L, "French", start, end))
.isInstanceOf(RuntimeException.class)
.hasMessageContaining("涓嶅彲棰勭害");
.hasMessageContaining("不可预约");
verify(reservationMapper, never()).insert(org.mockito.ArgumentMatchers.any(AppointmentReservationDO.class));
}
@@ -100,12 +104,12 @@ class AppointmentCapacityServiceImplTest {
void reserveRejectsWhenCoveringScheduleHasZeroCapacity() {
LocalDateTime start = LocalDateTime.of(2026, 6, 1, 10, 0);
LocalDateTime end = start.plusHours(1);
when(scheduleMapper.selectCoveringSchedule(9L, 30L, start.toLocalDate(), start.toLocalTime(), end.toLocalTime()))
when(scheduleMapper.selectCoveringScheduleForUpdate(9L, 30L, start.toLocalDate(), start.toLocalTime(), end.toLocalTime()))
.thenReturn(schedule(0));
assertThatThrownBy(() -> service.reserveOrThrow(1L, 10L, 9L, 30L, "French", start, end))
.isInstanceOf(RuntimeException.class)
.hasMessageContaining("涓嶅彲棰勭害");
.hasMessageContaining("不可预约");
verify(reservationMapper, never()).insert(org.mockito.ArgumentMatchers.any(AppointmentReservationDO.class));
}
@@ -114,9 +118,9 @@ class AppointmentCapacityServiceImplTest {
void moveReservationRechecksNewArtistCapacityBeforeUpdatingArtist() {
LocalDateTime start = LocalDateTime.of(2026, 6, 1, 10, 0);
LocalDateTime end = start.plusHours(1);
when(scheduleMapper.selectCoveringSchedule(9L, 31L, start.toLocalDate(), start.toLocalTime(), end.toLocalTime()))
when(scheduleMapper.selectCoveringScheduleForUpdate(9L, 31L, start.toLocalDate(), start.toLocalTime(), end.toLocalTime()))
.thenReturn(schedule(1));
when(reservationMapper.countOverlappingActiveForUpdateExcludingOrderItem(31L, 10L, start, end)).thenReturn(0);
when(reservationMapper.countOverlappingActiveExcludingOrderItem(31L, 10L, start, end)).thenReturn(0);
when(reservationMapper.updateActiveReservationForOrderItem(10L, 1L, 9L, 31L, "French", start, end, "CONFIRMED"))
.thenReturn(1);
@@ -0,0 +1,135 @@
package com.xiaowang.yuminailcore.modules.security;
import com.xiaowang.yuminailcore.annotation.RequirePermission;
import com.xiaowang.yuminailcore.modules.auth.controller.front.LoginIdentityController;
import com.xiaowang.yuminailcore.modules.auth.service.LoginIdentityService;
import com.xiaowang.yuminailcore.modules.marketing.controller.front.VipBenefitController;
import com.xiaowang.yuminailcore.modules.marketing.controller.front.VipInfoController;
import com.xiaowang.yuminailcore.modules.marketing.service.VipBenefitService;
import com.xiaowang.yuminailcore.modules.marketing.service.VipInfoService;
import com.xiaowang.yuminailcore.modules.security.support.AdminScopeHelper;
import com.xiaowang.yuminailcore.modules.shop.support.UserShopBindingSupport;
import com.xiaowang.yuminailcore.modules.user.entity.UserDO;
import org.junit.jupiter.api.Test;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class SensitiveControllerPermissionTest {
@Test
void sensitiveLoginIdentityEndpointsRequireUserManagementPermissions() {
assertPermission(LoginIdentityController.class, "createLoginIdentity", "user:create");
assertPermission(LoginIdentityController.class, "updateLoginIdentity", "user:edit");
assertPermission(LoginIdentityController.class, "deleteLoginIdentity", "user:delete");
assertPermission(LoginIdentityController.class, "getLoginIdentityById", "user:view");
assertPermission(LoginIdentityController.class, "listAllLoginIdentities", "user:view");
assertPermission(LoginIdentityController.class, "listLoginIdentitiesByUserId", "user:view");
assertPermission(LoginIdentityController.class, "listLoginIdentitiesByLoginMethod", "user:view");
}
@Test
void sensitiveVipEndpointsRequireVipManagementPermissions() {
for (Class<?> controller : List.of(VipBenefitController.class, VipInfoController.class)) {
Arrays.stream(controller.getDeclaredMethods())
.filter(SensitiveControllerPermissionTest::isRequestHandler)
.forEach(method -> assertThat(method.getAnnotation(RequirePermission.class))
.as("%s#%s", controller.getSimpleName(), method.getName())
.extracting(RequirePermission::value)
.isEqualTo("user:vip:manage"));
}
}
@Test
void loginIdentityListScopesStoreUsersByCurrentShop() {
LoginIdentityService service = mock(LoginIdentityService.class);
AdminScopeHelper scopeHelper = mock(AdminScopeHelper.class);
UserShopBindingSupport bindingSupport = mock(UserShopBindingSupport.class);
LoginIdentityController controller = new LoginIdentityController(service, scopeHelper, bindingSupport);
HttpServletRequest request = mock(HttpServletRequest.class);
UserDO storeUser = currentStoreUser();
when(scopeHelper.getCurrentUser(request)).thenReturn(storeUser);
when(scopeHelper.isPlatformAdmin(storeUser)).thenReturn(false);
when(scopeHelper.getManagedShopId(storeUser)).thenReturn(7L);
when(bindingSupport.listUserIdsByShopId(7L, true)).thenReturn(List.of(11L, 12L));
controller.listAllLoginIdentities(request);
verify(service).listLoginIdentitiesByUserIds(List.of(11L, 12L));
verify(service, never()).listAllLoginIdentities();
}
@Test
void vipInfoListScopesStoreUsersByCurrentShop() {
VipInfoService service = mock(VipInfoService.class);
AdminScopeHelper scopeHelper = mock(AdminScopeHelper.class);
UserShopBindingSupport bindingSupport = mock(UserShopBindingSupport.class);
VipInfoController controller = new VipInfoController(service, scopeHelper, bindingSupport);
HttpServletRequest request = mock(HttpServletRequest.class);
UserDO storeUser = currentStoreUser();
when(scopeHelper.getCurrentUser(request)).thenReturn(storeUser);
when(scopeHelper.isPlatformAdmin(storeUser)).thenReturn(false);
when(scopeHelper.getManagedShopId(storeUser)).thenReturn(7L);
when(bindingSupport.listUserIdsByShopId(7L, true)).thenReturn(List.of(11L, 12L));
controller.listAllVipInfos(request);
verify(service).listVipInfosByUserIds(List.of(11L, 12L));
verify(service, never()).listAllVipInfos();
}
@Test
void vipBenefitRequiresPlatformAdminBecauseBenefitHasNoShopScope() {
VipBenefitService service = mock(VipBenefitService.class);
AdminScopeHelper scopeHelper = mock(AdminScopeHelper.class);
VipBenefitController controller = new VipBenefitController(service, scopeHelper);
HttpServletRequest request = mock(HttpServletRequest.class);
UserDO storeUser = currentStoreUser();
when(scopeHelper.getCurrentUser(request)).thenReturn(storeUser);
controller.listAllVipBenefits(request);
verify(scopeHelper).requirePlatformAdmin(storeUser, "只有平台管理员可以维护全局VIP权益配置");
}
private static void assertPermission(Class<?> controller, String methodName, String permission) {
Method method = Arrays.stream(controller.getDeclaredMethods())
.filter(candidate -> candidate.getName().equals(methodName))
.findFirst()
.orElseThrow();
assertThat(method.getAnnotation(RequirePermission.class))
.as("%s#%s", controller.getSimpleName(), methodName)
.extracting(RequirePermission::value)
.isEqualTo(permission);
}
private static boolean isRequestHandler(Method method) {
return method.isAnnotationPresent(PostMapping.class)
|| method.isAnnotationPresent(PutMapping.class)
|| method.isAnnotationPresent(DeleteMapping.class)
|| method.isAnnotationPresent(GetMapping.class);
}
private static UserDO currentStoreUser() {
UserDO user = new UserDO();
user.setId(2L);
user.setType(2);
user.setShopId(7L);
return user;
}
}