This commit is contained in:
Ray Hao 2024-03-05 10:14:46 +08:00
commit a5265a0276
14 changed files with 120 additions and 99 deletions

View File

@ -50,7 +50,7 @@ public class OrderControllerTest {
@Autowired
private RestTemplate restTemplate;
private final String mobile = "18866668888";// 商城会员手机号
private final String verifyCode = "666666";// 短信验证码666666是免校验验证码
private final String code = "666666";// 短信验证码666666是免校验验证码
private final Long skuId = 1L;// 购买商品ID
@ -61,7 +61,7 @@ public class OrderControllerTest {
void testPurchaseFlow_Normal() throws Exception {
// 会员登录
String accessToken = acquireTokenByLogin(mobile, verifyCode); // 获取 accessToken填充请求头用于身份认证
String accessToken = acquireTokenByLogin(mobile, code); // 获取 accessToken填充请求头用于身份认证
HttpHeaders headers = new HttpHeaders();
headers.setBearerAuth(accessToken);
@ -86,7 +86,7 @@ public class OrderControllerTest {
void testPurchaseFlow_PaymentTimeout() throws Exception {
// 会员登录
String accessToken = acquireTokenByLogin(mobile, verifyCode); // 获取 accessToken填充请求头用于身份认证
String accessToken = acquireTokenByLogin(mobile, code); // 获取 accessToken填充请求头用于身份认证
HttpHeaders headers = new HttpHeaders();
headers.setBearerAuth(accessToken);
@ -204,10 +204,10 @@ public class OrderControllerTest {
* 登录获取访问令牌
*
* @param mobile 手机号
* @param verifyCode 短信验证码
* @param code 短信验证码
* @return
*/
private String acquireTokenByLogin(String mobile, String verifyCode) {
private String acquireTokenByLogin(String mobile, String code) {
String clientId = "mall-app";
String clientSecret = "123456";
String tokenUrl = "http://localhost:9000/oauth2/token";
@ -222,7 +222,7 @@ public class OrderControllerTest {
requestBody.add("client_id", clientId);
requestBody.add("client_secret", clientSecret);
requestBody.add("mobile", mobile);
requestBody.add("code", verifyCode);
requestBody.add("code", code);
// 创建 Basic Auth 头部
String authHeader = clientId + ":" + clientSecret;

View File

@ -30,8 +30,8 @@ public class PmsSpuController {
@Operation(summary = "商品分页列表")
@GetMapping("/page")
public PageResult getSpuPage(SpuPageQuery queryParams) {
IPage<PmsSpuPageVO> result = spuService.getSpuPage(queryParams);
public PageResult listPagedSpu(SpuPageQuery queryParams) {
IPage<PmsSpuPageVO> result = spuService.listPagedSpu(queryParams);
return PageResult.success(result);
}

View File

@ -29,8 +29,8 @@ public class SpuController {
@Operation(summary = "商品分页列表")
@GetMapping("/pages")
public PageResult getSpuPageForApp(SpuPageQuery queryParams) {
IPage<SpuPageVO> result = spuService.getSpuPageForApp(queryParams);
public PageResult<SpuPageVO> listPagedSpuForApp(SpuPageQuery queryParams) {
IPage<SpuPageVO> result = spuService.listPagedSpuForApp(queryParams);
return PageResult.success(result);
}

View File

@ -14,22 +14,22 @@ import java.util.List;
public interface PmsSpuMapper extends BaseMapper<PmsSpu> {
/**
* Admin- 商品分页列表
* Admin-商品分页列表
*
* @param page
* @param queryParams
* @return
* @param page 分页参数
* @param queryParams 查询参数
* @return 商品分页列表
*/
List<PmsSpuPageVO> getSpuPage(Page<PmsSpuPageVO> page, SpuPageQuery queryParams);
List<PmsSpuPageVO> listPagedSpu(Page<PmsSpuPageVO> page, SpuPageQuery queryParams);
/**
* 应用端商品分页列表
* APP-商品分页列表
*
* @param page
* @param queryParams
* @return
* @param page 分页参数
* @param queryParams 查询参数
* @return 商品分页列表
*/
List<SpuPageVO> getSpuPageForApp(Page<SpuPageVO> page, SpuPageQuery queryParams);
List<SpuPageVO> listPagedSpuForApp(Page<SpuPageVO> page, SpuPageQuery queryParams);
}

View File

@ -24,7 +24,7 @@ public interface SpuService extends IService<PmsSpu> {
* @param queryParams
* @return
*/
IPage<PmsSpuPageVO> getSpuPage(SpuPageQuery queryParams);
IPage<PmsSpuPageVO> listPagedSpu(SpuPageQuery queryParams);
/**
* 应用端商品分页列表
@ -32,7 +32,7 @@ public interface SpuService extends IService<PmsSpu> {
* @param queryParams
* @return
*/
IPage<SpuPageVO> getSpuPageForApp(SpuPageQuery queryParams);
IPage<SpuPageVO> listPagedSpuForApp(SpuPageQuery queryParams);
/**

View File

@ -33,12 +33,11 @@ import org.springframework.transaction.annotation.Transactional;
import java.util.*;
import java.util.stream.Collectors;
/**
* 商品业务实现类
*
* @author <a href="mailto:xianrui0365@163.com">haoxr</a>
* @date 2021/8/8
* @author Ray Hao
* @since 2021/08/08
*/
@Service
@RequiredArgsConstructor
@ -47,35 +46,33 @@ public class SpuServiceImpl extends ServiceImpl<PmsSpuMapper, PmsSpu> implements
private final SkuService skuService;
private final SpuAttributeService spuAttributeService;
private final MemberFeignClient memberFeignClient;
private final SpuConverter spuConverter;
private final SpuAttributeConverter spuAttributeConverter;
/**
* Admin-商品分页列表
*
* @param queryParams
* @return
* @param queryParams 查询参数
* @return 商品分页列表 IPage<PmsSpuPageVO>
*/
@Override
public IPage<PmsSpuPageVO> getSpuPage(SpuPageQuery queryParams) {
public IPage<PmsSpuPageVO> listPagedSpu(SpuPageQuery queryParams) {
Page<PmsSpuPageVO> page = new Page<>(queryParams.getPageNum(), queryParams.getPageSize());
List<PmsSpuPageVO> list = this.baseMapper.getSpuPage(page, queryParams);
List<PmsSpuPageVO> list = this.baseMapper.listPagedSpu(page, queryParams);
page.setRecords(list);
return page;
}
/**
* 应用端商品分页列表
* APP-商品分页列表
*
* @param queryParams
* @return
* @param queryParams 查询参数
* @return 商品分页列表 IPage<SpuPageVO>
*/
@Override
public IPage<SpuPageVO> getSpuPageForApp(SpuPageQuery queryParams) {
public IPage<SpuPageVO> listPagedSpuForApp(SpuPageQuery queryParams) {
Page<SpuPageVO> page = new Page<>(queryParams.getPageNum(), queryParams.getPageSize());
List<SpuPageVO> list = this.baseMapper.getSpuPageForApp(page, queryParams);
List<SpuPageVO> list = this.baseMapper.listPagedSpuForApp(page, queryParams);
page.setRecords(list);
return page;
}
@ -84,7 +81,7 @@ public class SpuServiceImpl extends ServiceImpl<PmsSpuMapper, PmsSpu> implements
* App-获取商品详情
*
* @param spuId 商品ID
* @return
* @return 商品详情
*/
@Override
public SpuDetailVO getSpuDetailForApp(Long spuId) {
@ -178,7 +175,7 @@ public class SpuServiceImpl extends ServiceImpl<PmsSpuMapper, PmsSpu> implements
* 获取商品详情
*
* @param spuId 商品ID
* @return
* @return 商品详情
*/
@Override
public PmsSpuDetailVO getSpuDetail(Long spuId) {
@ -212,8 +209,8 @@ public class SpuServiceImpl extends ServiceImpl<PmsSpuMapper, PmsSpu> implements
/**
* 添加商品
*
* @param formData
* @return
* @param formData 商品表单
* @return 是否成功
*/
@Override
@Transactional
@ -245,7 +242,7 @@ public class SpuServiceImpl extends ServiceImpl<PmsSpuMapper, PmsSpu> implements
*
* @param spuId 商品ID
* @param formData 商品表单
* @return
* @return 是否成功
*/
@Transactional
@Override
@ -277,7 +274,7 @@ public class SpuServiceImpl extends ServiceImpl<PmsSpuMapper, PmsSpu> implements
* 删除商品
*
* @param ids 商品ID多个以英文逗号(,)分割
* @return
* @return 是否成功
*/
@Override
@Transactional
@ -301,7 +298,7 @@ public class SpuServiceImpl extends ServiceImpl<PmsSpuMapper, PmsSpu> implements
/**
* 获取商品秒杀接口
*
* @return
* @return 商品秒杀列表
*/
@Override
public List<SeckillingSpuVO> listSeckillingSpu() {
@ -309,27 +306,26 @@ public class SpuServiceImpl extends ServiceImpl<PmsSpuMapper, PmsSpu> implements
.select(PmsSpu::getId, PmsSpu::getName, PmsSpu::getPicUrl, PmsSpu::getPrice)
.orderByDesc(PmsSpu::getCreateTime)
);
List<SeckillingSpuVO> list = spuConverter.entity2SeckillingVO(entities);
return list;
return spuConverter.entity2SeckillingVO(entities);
}
/**
* 保存SKU需要替换提交表单中的临时规格ID
*
* @param goodsId
* @param skuList
* @param specTempIdIdMap
* @return
* @param spuId 商品ID
* @param skuList SKU列表
* @param specTempIdIdMap 临时规格ID和持久化数据库得到的规格ID的映射
* @return 是否成功
*/
private boolean saveSku(Long goodsId, List<PmsSku> skuList, Map<String, Long> specTempIdIdMap) {
private boolean saveSku(Long spuId, List<PmsSku> skuList, Map<String, Long> specTempIdIdMap) {
// 删除SKU
List<Long> formSkuIds = skuList.stream().map(PmsSku::getId).collect(Collectors.toList());
List<Long> formSkuIds = skuList.stream().map(PmsSku::getId).toList();
List<Long> dbSkuIds = skuService.list(new LambdaQueryWrapper<PmsSku>().eq(PmsSku::getSpuId, goodsId)
List<Long> dbSkuIds = skuService.list(new LambdaQueryWrapper<PmsSku>().eq(PmsSku::getSpuId, spuId)
.select(PmsSku::getId)).stream().map(PmsSku::getId)
.collect(Collectors.toList());
.toList();
List<Long> removeSkuIds = dbSkuIds.stream().filter(dbSkuId -> !formSkuIds.contains(dbSkuId)).collect(Collectors.toList());
@ -344,7 +340,7 @@ public class SpuServiceImpl extends ServiceImpl<PmsSpuMapper, PmsSpu> implements
.map(specId -> specId.startsWith(ProductConstants.SPEC_TEMP_ID_PREFIX) ? specTempIdIdMap.get(specId) + "" : specId)
.collect(Collectors.joining("_"));
sku.setSpecIds(specIds);
sku.setSpuId(goodsId);
sku.setSpuId(spuId);
return sku;
}).collect(Collectors.toList());
return skuService.saveOrUpdateBatch(pmsSkuList);
@ -366,14 +362,14 @@ public class SpuServiceImpl extends ServiceImpl<PmsSpuMapper, PmsSpu> implements
List<Long> retainAttrIds = attrList.stream()
.filter(item -> item.getId() != null)
.map(item -> Convert.toLong(item.getId()))
.collect(Collectors.toList());
.toList();
// 1.2 获取原商品属性ID集合
List<Long> originAttrIds = spuAttributeService.list(new LambdaQueryWrapper<PmsSpuAttribute>()
.eq(PmsSpuAttribute::getSpuId, spuId).eq(PmsSpuAttribute::getType, AttributeTypeEnum.ATTR.getValue())
.select(PmsSpuAttribute::getId))
.stream()
.map(PmsSpuAttribute::getId)
.collect(Collectors.toList());
.toList();
// 1.3 需要删除的商品属性原商品属性-此次提交保留的属性
List<Long> removeAttrValIds = originAttrIds.stream()
.filter(id -> !retainAttrIds.contains(id))
@ -413,7 +409,7 @@ public class SpuServiceImpl extends ServiceImpl<PmsSpuMapper, PmsSpu> implements
List<Long> retainSpuSpecIds = specList.stream()
.filter(item -> !item.getId().startsWith(ProductConstants.SPEC_TEMP_ID_PREFIX))
.map(item -> Convert.toLong(item.getId()))
.collect(Collectors.toList());
.toList();
// 1.2 原商品规格
List<Long> originSpuSpecIds = spuAttributeService.list(new LambdaQueryWrapper<PmsSpuAttribute>()
@ -421,7 +417,7 @@ public class SpuServiceImpl extends ServiceImpl<PmsSpuMapper, PmsSpu> implements
.eq(PmsSpuAttribute::getType, AttributeTypeEnum.SPEC.getValue())
.select(PmsSpuAttribute::getId))
.stream().map(PmsSpuAttribute::getId)
.collect(Collectors.toList());
.toList();
// 1.3 需要删除的商品规格原商品规格-此次提交保留的规格
List<Long> removeSpuSpecIds = originSpuSpecIds.stream().filter(id -> !retainSpuSpecIds.contains(id))

View File

@ -33,7 +33,7 @@
</resultMap>
<!--Admin-商品分页列表-->
<select id="getSpuPage" resultMap="BaseResultMap">
<select id="listPagedSpu" resultMap="BaseResultMap">
SELECT
t1.id,
t1.name,
@ -65,7 +65,7 @@
<!--「应用端」商品分页列表-->
<select id="listSpuPages" resultType="com.youlai.mall.pms.model.vo.SpuPageVO">
<select id="listPagedSpuForApp" resultType="com.youlai.mall.pms.model.vo.SpuPageVO">
SELECT
id,
NAME,
@ -84,7 +84,7 @@
</where>
ORDER BY
<if test='queryParams.sortField!=null and queryParams.sortField.trim() neq "" and queryParams.sortField !=null and queryParams.sort.trim() neq ""'>
#{queryParams.sortField} #{queryParams.sort} ,
${queryParams.sortField} ${queryParams.sort} ,
</if>
create_time desc
</select>

View File

@ -66,11 +66,11 @@ public class SmsAuthenticationConverter implements AuthenticationConverter {
}
// 验证码(必需)
String verifyCode = parameters.getFirst(SmsParameterNames.VERIFY_CODE);
if (StrUtil.isBlank(verifyCode)) {
String code = parameters.getFirst(SmsParameterNames.CODE);
if (StrUtil.isBlank(code)) {
OAuth2EndpointUtils.throwError(
OAuth2ErrorCodes.INVALID_REQUEST,
SmsParameterNames.VERIFY_CODE,
SmsParameterNames.CODE,
OAuth2EndpointUtils.ACCESS_TOKEN_REQUEST_ERROR_URI);
}

View File

@ -86,13 +86,13 @@ public class SmsAuthenticationProvider implements AuthenticationProvider {
// 短信验证码校验
Map<String, Object> additionalParameters = smsAuthenticationToken.getAdditionalParameters();
String mobile = (String) additionalParameters.get(SmsParameterNames.MOBILE);
String verifyCode = (String) additionalParameters.get(SmsParameterNames.VERIFY_CODE);
String code = (String) additionalParameters.get(SmsParameterNames.CODE);
if (!verifyCode.equals("666666")) { // 666666 是后门因为短信收费正式环境删除这个if
if (!code.equals("666666")) { // 666666 是后门因为短信收费正式环境删除这个if
String codeKey = RedisConstants.LOGIN_SMS_CODE_PREFIX + mobile;
String cacheCode = (String) redisTemplate.opsForValue().get(codeKey);
if (!StrUtil.equals(verifyCode, cacheCode)) {
if (!StrUtil.equals(code, cacheCode)) {
throw new OAuth2AuthenticationException("验证码错误");
}
}

View File

@ -32,7 +32,7 @@ public final class SmsParameterNames {
/**
* 验证码
*/
public static final String VERIFY_CODE = "verifyCode";
public static final String CODE = "code";
private SmsParameterNames() {

View File

@ -32,7 +32,7 @@ public class SmsAuthenticationTests {
this.mvc.perform(post("/oauth2/token")
.param(OAuth2ParameterNames.GRANT_TYPE, "sms_code")
.param("mobile", "18866668888")
.param("verifyCode", "666666")
.param("code", "666666")
.headers(headers))
.andDo(print())
.andExpect(status().isOk())

View File

@ -15,7 +15,7 @@ import java.io.IOException;
* 自定义 token 无效异常
*
* @author haoxr
* @date 2022/11/13
* @since 2022/11/13
*/
@Component
public class MyAuthenticationEntryPoint implements AuthenticationEntryPoint {
@ -23,16 +23,8 @@ public class MyAuthenticationEntryPoint implements AuthenticationEntryPoint {
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException)
throws IOException {
response.setContentType("application/json");
int status = response.getStatus();
ObjectMapper mapper = new ObjectMapper();
if (HttpServletResponse.SC_NOT_FOUND == status) {
response.setStatus(HttpServletResponse.SC_NOT_FOUND);
mapper.writeValue(response.getOutputStream(), Result.failed(ResultCode.RESOURCE_NOT_FOUND));
} else {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
mapper.writeValue(response.getOutputStream(), Result.failed(ResultCode.TOKEN_INVALID));
}
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
mapper.writeValue(response.getOutputStream(), Result.failed(ResultCode.TOKEN_INVALID));
}
}

View File

@ -21,18 +21,27 @@ import java.util.stream.Collectors;
public class SecurityUtils {
public static Long getUserId() {
return Convert.toLong(getTokenAttributes().get("userId"));
Map<String, Object> tokenAttributes = getTokenAttributes();
if (tokenAttributes != null) {
return Convert.toLong(tokenAttributes.get("userId"));
}
return null;
}
public static String getUsername() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
return authentication.getName();
if (authentication != null) {
return authentication.getName();
}
return null;
}
public static Map<String, Object> getTokenAttributes() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
JwtAuthenticationToken jwtAuthenticationToken = (JwtAuthenticationToken) authentication;
return jwtAuthenticationToken.getTokenAttributes();
if (authentication instanceof JwtAuthenticationToken jwtAuthenticationToken) {
return jwtAuthenticationToken.getTokenAttributes();
}
return null;
}
@ -41,30 +50,45 @@ public class SecurityUtils {
*/
public static Set<String> getRoles() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
return AuthorityUtils.authorityListToSet(authentication.getAuthorities())
.stream()
.collect(Collectors.collectingAndThen(Collectors.toSet(), Collections::unmodifiableSet));
if (authentication != null) {
return AuthorityUtils.authorityListToSet(authentication.getAuthorities())
.stream()
.collect(Collectors.collectingAndThen(Collectors.toSet(), Collections::unmodifiableSet));
}
return null;
}
/**
* 获取部门ID
*/
public static Long getDeptId() {
return Convert.toLong(getTokenAttributes().get("deptId"));
Map<String, Object> tokenAttributes = getTokenAttributes();
if (tokenAttributes != null) {
return Convert.toLong(tokenAttributes.get("deptId"));
}
return null;
}
public static boolean isRoot() {
return getRoles().contains(SystemConstants.ROOT_ROLE_CODE);
Set<String> roles = getRoles();
return roles != null && roles.contains(SystemConstants.ROOT_ROLE_CODE);
}
public static String getJti() {
return String.valueOf(getTokenAttributes().get("jti"));
Map<String, Object> tokenAttributes = getTokenAttributes();
if (tokenAttributes != null) {
return String.valueOf(tokenAttributes.get("jti"));
}
return null;
}
public static Long getExp() {
return Convert.toLong(getTokenAttributes().get("exp"));
Map<String, Object> tokenAttributes = getTokenAttributes();
if (tokenAttributes != null) {
return Convert.toLong(tokenAttributes.get("exp"));
}
return null;
}
/**
@ -74,7 +98,11 @@ public class SecurityUtils {
* @see com.youlai.common.mybatis.enums.DataScopeEnum
*/
public static Integer getDataScope() {
return Convert.toInt(getTokenAttributes().get("dataScope"));
Map<String, Object> tokenAttributes = getTokenAttributes();
if (tokenAttributes != null) {
return Convert.toInt(tokenAttributes.get("dataScope"));
}
return null;
}
/**
@ -83,6 +111,10 @@ public class SecurityUtils {
* @return 会员ID
*/
public static Long getMemberId() {
return Convert.toLong(getTokenAttributes().get("memberId"));
Map<String, Object> tokenAttributes = getTokenAttributes();
if (tokenAttributes != null) {
return Convert.toLong(tokenAttributes.get("memberId"));
}
return null;
}
}

View File

@ -23,6 +23,7 @@ import org.springframework.web.servlet.NoHandlerFoundException;
import jakarta.servlet.ServletException;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.ConstraintViolationException;
import java.sql.SQLSyntaxErrorException;
import java.util.concurrent.CompletionException;
import java.util.regex.Matcher;
@ -201,15 +202,15 @@ public class GlobalExceptionHandler {
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(Exception.class)
public <T> Result<T> handleException(Exception e) {
e.printStackTrace();
log.error("unknown exception:{}", e.getMessage(), e);
String errorMsg = e.getMessage();
if (StrUtil.isNotBlank(errorMsg) && errorMsg.contains("denied to user")) {
return Result.failed(ResultCode.FORBIDDEN_OPERATION);
}else{
log.error("unknown exception");
errorMsg=e.getCause().getMessage();
return Result.failed(errorMsg);
}
if (StrUtil.isBlank(errorMsg)) {
errorMsg = "系统异常";
}
return Result.failed(errorMsg);
}
/**