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

View File

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

View File

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

View File

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

View File

@ -33,7 +33,7 @@
</resultMap> </resultMap>
<!--Admin-商品分页列表--> <!--Admin-商品分页列表-->
<select id="getSpuPage" resultMap="BaseResultMap"> <select id="listPagedSpu" resultMap="BaseResultMap">
SELECT SELECT
t1.id, t1.id,
t1.name, 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 SELECT
id, id,
NAME, NAME,
@ -84,7 +84,7 @@
</where> </where>
ORDER BY ORDER BY
<if test='queryParams.sortField!=null and queryParams.sortField.trim() neq "" and queryParams.sortField !=null and queryParams.sort.trim() neq ""'> <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> </if>
create_time desc create_time desc
</select> </select>

View File

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

View File

@ -86,13 +86,13 @@ public class SmsAuthenticationProvider implements AuthenticationProvider {
// 短信验证码校验 // 短信验证码校验
Map<String, Object> additionalParameters = smsAuthenticationToken.getAdditionalParameters(); Map<String, Object> additionalParameters = smsAuthenticationToken.getAdditionalParameters();
String mobile = (String) additionalParameters.get(SmsParameterNames.MOBILE); 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 codeKey = RedisConstants.LOGIN_SMS_CODE_PREFIX + mobile;
String cacheCode = (String) redisTemplate.opsForValue().get(codeKey); String cacheCode = (String) redisTemplate.opsForValue().get(codeKey);
if (!StrUtil.equals(verifyCode, cacheCode)) { if (!StrUtil.equals(code, cacheCode)) {
throw new OAuth2AuthenticationException("验证码错误"); 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() { private SmsParameterNames() {

View File

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

View File

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

View File

@ -21,19 +21,28 @@ import java.util.stream.Collectors;
public class SecurityUtils { public class SecurityUtils {
public static Long getUserId() { 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() { public static String getUsername() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication != null) {
return authentication.getName(); return authentication.getName();
} }
return null;
}
public static Map<String, Object> getTokenAttributes() { public static Map<String, Object> getTokenAttributes() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
JwtAuthenticationToken jwtAuthenticationToken = (JwtAuthenticationToken) authentication; if (authentication instanceof JwtAuthenticationToken jwtAuthenticationToken) {
return jwtAuthenticationToken.getTokenAttributes(); return jwtAuthenticationToken.getTokenAttributes();
} }
return null;
}
/** /**
@ -41,30 +50,45 @@ public class SecurityUtils {
*/ */
public static Set<String> getRoles() { public static Set<String> getRoles() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication != null) {
return AuthorityUtils.authorityListToSet(authentication.getAuthorities()) return AuthorityUtils.authorityListToSet(authentication.getAuthorities())
.stream() .stream()
.collect(Collectors.collectingAndThen(Collectors.toSet(), Collections::unmodifiableSet)); .collect(Collectors.collectingAndThen(Collectors.toSet(), Collections::unmodifiableSet));
} }
return null;
}
/** /**
* 获取部门ID * 获取部门ID
*/ */
public static Long getDeptId() { 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() { 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() { 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() { 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 * @see com.youlai.common.mybatis.enums.DataScopeEnum
*/ */
public static Integer getDataScope() { 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 * @return 会员ID
*/ */
public static Long getMemberId() { 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.servlet.ServletException;
import jakarta.validation.ConstraintViolation; import jakarta.validation.ConstraintViolation;
import jakarta.validation.ConstraintViolationException; import jakarta.validation.ConstraintViolationException;
import java.sql.SQLSyntaxErrorException; import java.sql.SQLSyntaxErrorException;
import java.util.concurrent.CompletionException; import java.util.concurrent.CompletionException;
import java.util.regex.Matcher; import java.util.regex.Matcher;
@ -201,15 +202,15 @@ public class GlobalExceptionHandler {
@ResponseStatus(HttpStatus.BAD_REQUEST) @ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(Exception.class) @ExceptionHandler(Exception.class)
public <T> Result<T> handleException(Exception e) { public <T> Result<T> handleException(Exception e) {
e.printStackTrace(); log.error("unknown exception:{}", e.getMessage(), e);
String errorMsg = e.getMessage(); String errorMsg = e.getMessage();
if (StrUtil.isNotBlank(errorMsg) && errorMsg.contains("denied to user")) { if (StrUtil.isNotBlank(errorMsg) && errorMsg.contains("denied to user")) {
return Result.failed(ResultCode.FORBIDDEN_OPERATION); 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);
} }
/** /**