refactor: 优化部分代码

修复 Sonar、Codacy 扫描问题:补充部分泛型、调整部分 Boolean 类型判断、将部分不必要的(无集合长度变动) collect(Collectors.toList()); 转换为 toList()
This commit is contained in:
Charles7c 2024-02-03 11:43:05 +08:00
parent 3d77aa91ee
commit 6d959f5e3e
17 changed files with 93 additions and 104 deletions
continew-admin-monitor/src/main/java/top/charles7c/continew/admin/monitor/service/impl
continew-admin-system/src/main/java/top/charles7c/continew/admin
continew-admin-tool/src/main/java/top/charles7c/continew/admin/tool/service/impl
continew-admin-webapi/src/main/java/top/charles7c/continew/admin/webapi

View File

@ -40,7 +40,6 @@ import top.charles7c.continew.starter.extension.crud.model.resp.PageResp;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* 系统日志业务实现
@ -64,7 +63,7 @@ public class LogServiceImpl implements LogService {
List<String> columnNameList = fieldNameList.stream()
.filter(n -> !n.endsWith(SysConstants.DESCRIPTION_FIELD_SUFFIX))
.map(StrUtil::toUnderlineCase)
.collect(Collectors.toList());
.toList();
queryWrapper.select(columnNameList);
// 分页查询
IPage<LogDO> page = logMapper.selectPage(pageQuery.toPage(), queryWrapper);
@ -81,7 +80,7 @@ public class LogServiceImpl implements LogService {
List<String> columnNameList = fieldNameList.stream()
.filter(n -> !n.endsWith(SysConstants.DESCRIPTION_FIELD_SUFFIX))
.map(StrUtil::toUnderlineCase)
.collect(Collectors.toList());
.toList();
queryWrapper.select(columnNameList);
// 分页查询
IPage<LogDO> page = logMapper.selectPage(pageQuery.toPage(), queryWrapper);
@ -97,7 +96,7 @@ public class LogServiceImpl implements LogService {
List<String> columnNameList = fieldNameList.stream()
.filter(n -> !n.endsWith(SysConstants.DESCRIPTION_FIELD_SUFFIX))
.map(StrUtil::toUnderlineCase)
.collect(Collectors.toList());
.toList();
queryWrapper.select(columnNameList);
// 分页查询
IPage<LogDO> page = logMapper.selectPage(pageQuery.toPage(), queryWrapper);

View File

@ -56,7 +56,6 @@ import top.charles7c.continew.starter.extension.crud.util.TreeUtils;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;
/**
* 登录业务实现
@ -158,9 +157,7 @@ public class LoginServiceImpl implements LoginService {
} else {
roleCodeSet.forEach(roleCode -> menuSet.addAll(menuService.listByRoleCode(roleCode)));
}
List<MenuResp> menuList = menuSet.stream()
.filter(m -> !MenuTypeEnum.BUTTON.equals(m.getType()))
.collect(Collectors.toList());
List<MenuResp> menuList = menuSet.stream().filter(m -> !MenuTypeEnum.BUTTON.equals(m.getType())).toList();
// 构建路由树
TreeField treeField = MenuResp.class.getDeclaredAnnotation(TreeField.class);
TreeNodeConfig treeNodeConfig = TreeUtils.genTreeNodeConfig(treeField);
@ -175,7 +172,7 @@ public class LoginServiceImpl implements LoginService {
MetaResp metaResp = new MetaResp();
metaResp.setLocale(m.getTitle());
metaResp.setIcon(m.getIcon());
metaResp.setIgnoreCache(!m.getIsCache());
metaResp.setIgnoreCache(Boolean.FALSE.equals(m.getIsCache()));
metaResp.setHideInMenu(m.getIsHidden());
metaResp.setOrder(m.getSort());
tree.putExtra("meta", metaResp);

View File

@ -21,6 +21,7 @@ import top.charles7c.continew.admin.common.model.resp.LabelValueResp;
import top.charles7c.continew.admin.system.model.entity.DictItemDO;
import top.charles7c.continew.starter.data.mybatis.plus.base.BaseMapper;
import java.io.Serializable;
import java.util.List;
/**
@ -37,5 +38,5 @@ public interface DictItemMapper extends BaseMapper<DictItemDO> {
* @param dictCode 字典编码
* @return 字典项列表
*/
List<LabelValueResp> listByDictCode(@Param("dictCode") String dictCode);
List<LabelValueResp<Serializable>> listByDictCode(@Param("dictCode") String dictCode);
}

View File

@ -25,6 +25,7 @@ import top.charles7c.continew.admin.system.model.resp.DictItemResp;
import top.charles7c.continew.starter.extension.crud.service.BaseService;
import top.charles7c.continew.starter.extension.crud.service.IService;
import java.io.Serializable;
import java.util.List;
/**
@ -49,7 +50,7 @@ public interface DictItemService extends BaseService<DictItemResp, DictItemDetai
* @param dictCode 字典编码
* @return 字典项列表
*/
List<LabelValueResp> listByDictCode(String dictCode);
List<LabelValueResp<Serializable>> listByDictCode(String dictCode);
/**
* 根据字典 ID 列表删除

View File

@ -30,6 +30,7 @@ import top.charles7c.continew.starter.core.util.validate.CheckUtils;
import top.charles7c.continew.starter.extension.crud.service.impl.BaseServiceImpl;
import top.charles7c.continew.starter.extension.crud.model.query.SortQuery;
import java.io.Serializable;
import java.util.List;
/**
@ -66,7 +67,7 @@ public class DictItemServiceImpl extends BaseServiceImpl<DictItemMapper, DictIte
}
@Override
public List<LabelValueResp> listByDictCode(String dictCode) {
public List<LabelValueResp<Serializable>> listByDictCode(String dictCode) {
return baseMapper.listByDictCode(dictCode);
}

View File

@ -16,17 +16,9 @@
package top.charles7c.continew.admin.system.service.impl;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import cn.hutool.core.collection.CollUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import top.charles7c.continew.admin.common.enums.MessageTypeEnum;
import top.charles7c.continew.admin.system.mapper.MessageUserMapper;
import top.charles7c.continew.admin.system.model.entity.MessageUserDO;
@ -35,6 +27,10 @@ import top.charles7c.continew.admin.system.model.resp.MessageUnreadResp;
import top.charles7c.continew.admin.system.service.MessageUserService;
import top.charles7c.continew.starter.core.util.validate.CheckUtils;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
/**
* 消息和用户关联业务实现
*
@ -78,7 +74,7 @@ public class MessageUserServiceImpl implements MessageUserService {
messageUser.setMessageId(messageId);
messageUser.setIsRead(false);
return messageUser;
}).collect(Collectors.toList());
}).toList();
baseMapper.insertBatch(messageUserList);
}

View File

@ -28,7 +28,6 @@ import top.charles7c.continew.admin.system.model.entity.RoleDeptDO;
import top.charles7c.continew.admin.system.service.RoleDeptService;
import java.util.List;
import java.util.stream.Collectors;
/**
* 角色和部门业务实现
@ -52,16 +51,14 @@ public class RoleDeptServiceImpl implements RoleDeptService {
.list()
.stream()
.map(RoleDeptDO::getDeptId)
.collect(Collectors.toList());
.toList();
if (CollUtil.isEmpty(CollUtil.disjunction(deptIds, oldDeptIdList))) {
return false;
}
// 删除原有关联
roleDeptMapper.lambdaUpdate().eq(RoleDeptDO::getRoleId, roleId).remove();
// 保存最新关联
List<RoleDeptDO> roleDeptList = deptIds.stream()
.map(deptId -> new RoleDeptDO(roleId, deptId))
.collect(Collectors.toList());
List<RoleDeptDO> roleDeptList = deptIds.stream().map(deptId -> new RoleDeptDO(roleId, deptId)).toList();
return roleDeptMapper.insertBatch(roleDeptList);
}

View File

@ -16,21 +16,18 @@
package top.charles7c.continew.admin.system.service.impl;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import cn.hutool.core.collection.CollUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import cn.hutool.core.collection.CollUtil;
import top.charles7c.continew.admin.system.mapper.RoleMenuMapper;
import top.charles7c.continew.admin.system.model.entity.RoleMenuDO;
import top.charles7c.continew.admin.system.service.RoleMenuService;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
/**
* 角色和菜单业务实现
*
@ -60,9 +57,7 @@ public class RoleMenuServiceImpl implements RoleMenuService {
// 删除原有关联
roleMenuMapper.lambdaUpdate().eq(RoleMenuDO::getRoleId, roleId).remove();
// 保存最新关联
List<RoleMenuDO> roleMenuList = menuIds.stream()
.map(menuId -> new RoleMenuDO(roleId, menuId))
.collect(Collectors.toList());
List<RoleMenuDO> roleMenuList = menuIds.stream().map(menuId -> new RoleMenuDO(roleId, menuId)).toList();
return roleMenuMapper.insertBatch(roleMenuList);
}

View File

@ -133,7 +133,7 @@ public class RoleServiceImpl extends BaseServiceImpl<RoleMapper, RoleDO, RoleRes
Long roleId = detail.getId();
if (SysConstants.ADMIN_ROLE_CODE.equals(detail.getCode())) {
List<MenuResp> list = menuService.list(null, null);
List<Long> menuIds = list.stream().map(MenuResp::getId).collect(Collectors.toList());
List<Long> menuIds = list.stream().map(MenuResp::getId).toList();
detail.setMenuIds(menuIds);
} else {
detail.setMenuIds(roleMenuService.listMenuIdByRoleIds(CollUtil.newArrayList(roleId)));
@ -152,7 +152,7 @@ public class RoleServiceImpl extends BaseServiceImpl<RoleMapper, RoleDO, RoleRes
@Override
public List<String> listNameByIds(List<Long> ids) {
List<RoleDO> roleList = baseMapper.lambdaQuery().select(RoleDO::getName).in(RoleDO::getId, ids).list();
return roleList.stream().map(RoleDO::getName).collect(Collectors.toList());
return roleList.stream().map(RoleDO::getName).toList();
}
@Override

View File

@ -167,10 +167,7 @@ public class StorageServiceImpl extends BaseServiceImpl<StorageMapper, StorageDO
* @return 是否存在
*/
private boolean isDefaultExists(Long id) {
return baseMapper.lambdaQuery()
.eq(StorageDO::getIsDefault, Boolean.TRUE)
.ne(null != id, StorageDO::getId, id)
.exists();
return baseMapper.lambdaQuery().eq(StorageDO::getIsDefault, true).ne(null != id, StorageDO::getId, id).exists();
}
/**

View File

@ -28,7 +28,6 @@ import top.charles7c.continew.admin.system.model.entity.UserRoleDO;
import top.charles7c.continew.admin.system.service.UserRoleService;
import java.util.List;
import java.util.stream.Collectors;
/**
* 用户和角色业务实现
@ -52,16 +51,14 @@ public class UserRoleServiceImpl implements UserRoleService {
.list()
.stream()
.map(UserRoleDO::getRoleId)
.collect(Collectors.toList());
.toList();
if (CollUtil.isEmpty(CollUtil.disjunction(roleIds, oldRoleIdList))) {
return false;
}
// 删除原有关联
userRoleMapper.lambdaUpdate().eq(UserRoleDO::getUserId, userId).remove();
// 保存最新关联
List<UserRoleDO> userRoleList = roleIds.stream()
.map(roleId -> new UserRoleDO(userId, roleId))
.collect(Collectors.toList());
List<UserRoleDO> userRoleList = roleIds.stream().map(roleId -> new UserRoleDO(userId, roleId)).toList();
return userRoleMapper.insertBatch(userRoleList);
}

View File

@ -75,6 +75,7 @@ public class UserServiceImpl extends BaseServiceImpl<UserMapper, UserDO, UserRes
private final PasswordEncoder passwordEncoder;
@Value("${avatar.support-suffix}")
private String[] avatarSupportSuffix;
private static final String CURRENT_PASSWORD_ERROR = "当前密码错误";
@Override
public Long add(UserDO user) {
@ -85,12 +86,13 @@ public class UserServiceImpl extends BaseServiceImpl<UserMapper, UserDO, UserRes
@Override
protected void beforeAdd(UserReq req) {
final String errorMsgTemplate = "新增失败,[{}] 已存在";
String username = req.getUsername();
CheckUtils.throwIf(this.isNameExists(username, null), "新增失败,[{}] 已存在", username);
CheckUtils.throwIf(this.isNameExists(username, null), errorMsgTemplate, username);
String email = req.getEmail();
CheckUtils.throwIf(StrUtil.isNotBlank(email) && this.isEmailExists(email, null), "新增失败,[{}] 已存在", email);
CheckUtils.throwIf(StrUtil.isNotBlank(email) && this.isEmailExists(email, null), errorMsgTemplate, email);
String phone = req.getPhone();
CheckUtils.throwIf(StrUtil.isNotBlank(phone) && this.isPhoneExists(phone, null), "新增失败,[{}] 已存在", phone);
CheckUtils.throwIf(StrUtil.isNotBlank(phone) && this.isPhoneExists(phone, null), errorMsgTemplate, phone);
req.setStatus(DisEnableStatusEnum.ENABLE);
req.setPassword(passwordEncoder.encode(req.getPassword()));
}
@ -107,12 +109,13 @@ public class UserServiceImpl extends BaseServiceImpl<UserMapper, UserDO, UserRes
@Transactional(rollbackFor = Exception.class)
@CacheUpdate(key = "#id", value = "#req.nickname", name = CacheConstants.USER_KEY_PREFIX)
public void update(UserReq req, Long id) {
final String errorMsgTemplate = "修改失败,[{}] 已存在";
String username = req.getUsername();
CheckUtils.throwIf(this.isNameExists(username, id), "修改失败,[{}] 已存在", username);
CheckUtils.throwIf(this.isNameExists(username, id), errorMsgTemplate, username);
String email = req.getEmail();
CheckUtils.throwIf(StrUtil.isNotBlank(email) && this.isEmailExists(email, id), "修改失败,[{}] 已存在", email);
CheckUtils.throwIf(StrUtil.isNotBlank(email) && this.isEmailExists(email, id), errorMsgTemplate, email);
String phone = req.getPhone();
CheckUtils.throwIf(StrUtil.isNotBlank(phone) && this.isPhoneExists(phone, id), "修改失败,[{}] 已存在", phone);
CheckUtils.throwIf(StrUtil.isNotBlank(phone) && this.isPhoneExists(phone, id), errorMsgTemplate, phone);
DisEnableStatusEnum newStatus = req.getStatus();
CheckUtils.throwIf(DisEnableStatusEnum.DISABLE.equals(newStatus) && ObjectUtil.equal(id, LoginHelper
.getUserId()), "不允许禁用当前用户");
@ -196,7 +199,7 @@ public class UserServiceImpl extends BaseServiceImpl<UserMapper, UserDO, UserRes
UserDO user = super.getById(id);
String password = user.getPassword();
if (StrUtil.isNotBlank(password)) {
CheckUtils.throwIf(!passwordEncoder.matches(oldPassword, password), "当前密码错误");
CheckUtils.throwIf(!passwordEncoder.matches(oldPassword, password), CURRENT_PASSWORD_ERROR);
}
// 更新密码和密码重置时间
LocalDateTime now = LocalDateTime.now();
@ -210,7 +213,7 @@ public class UserServiceImpl extends BaseServiceImpl<UserMapper, UserDO, UserRes
@Override
public void updatePhone(String newPhone, String currentPassword, Long id) {
UserDO user = super.getById(id);
CheckUtils.throwIf(!passwordEncoder.matches(currentPassword, user.getPassword()), "当前密码错误");
CheckUtils.throwIf(!passwordEncoder.matches(currentPassword, user.getPassword()), CURRENT_PASSWORD_ERROR);
Long count = baseMapper.lambdaQuery().eq(UserDO::getPhone, newPhone).count();
CheckUtils.throwIf(count > 0, "手机号已绑定其他账号,请更换其他手机号");
CheckUtils.throwIfEqual(newPhone, user.getPhone(), "新手机号不能与当前手机号相同");
@ -221,7 +224,7 @@ public class UserServiceImpl extends BaseServiceImpl<UserMapper, UserDO, UserRes
@Override
public void updateEmail(String newEmail, String currentPassword, Long id) {
UserDO user = super.getById(id);
CheckUtils.throwIf(!passwordEncoder.matches(currentPassword, user.getPassword()), "当前密码错误");
CheckUtils.throwIf(!passwordEncoder.matches(currentPassword, user.getPassword()), CURRENT_PASSWORD_ERROR);
Long count = baseMapper.lambdaQuery().eq(UserDO::getEmail, newEmail).count();
CheckUtils.throwIf(count > 0, "邮箱已绑定其他账号,请更换其他邮箱");
CheckUtils.throwIfEqual(newEmail, user.getEmail(), "新邮箱不能与当前邮箱相同");

View File

@ -131,13 +131,13 @@ public class GeneratorServiceImpl implements GeneratorService {
List<FieldConfigDO> fieldConfigList = fieldConfigMapper.selectListByTableName(tableName);
if (CollUtil.isEmpty(fieldConfigList)) {
Collection<Column> columnList = MetaUtils.getColumns(dataSource, tableName);
return columnList.stream().map(FieldConfigDO::new).collect(Collectors.toList());
return columnList.stream().map(FieldConfigDO::new).toList();
}
// 同步最新数据表列信息
if (Boolean.TRUE.equals(requireSync)) {
Collection<Column> columnList = MetaUtils.getColumns(dataSource, tableName);
// 移除已不存在的字段配置
List<String> columnNameList = columnList.stream().map(Column::getName).collect(Collectors.toList());
List<String> columnNameList = columnList.stream().map(Column::getName).toList();
fieldConfigList.removeIf(column -> !columnNameList.contains(column.getColumnName()));
// 新增或更新字段配置
Map<String, FieldConfigDO> fieldConfigMap = fieldConfigList.stream()
@ -168,13 +168,13 @@ public class GeneratorServiceImpl implements GeneratorService {
fieldConfigMapper.delete(Wrappers.lambdaQuery(FieldConfigDO.class).eq(FieldConfigDO::getTableName, tableName));
List<FieldConfigDO> fieldConfigList = req.getFieldConfigs();
for (FieldConfigDO fieldConfig : fieldConfigList) {
if (fieldConfig.getShowInForm()) {
if (Boolean.TRUE.equals(fieldConfig.getShowInForm())) {
CheckUtils.throwIfNull(fieldConfig.getFormType(), "字段 [{}] 的表单类型不能为空", fieldConfig.getFieldName());
} else {
// 在表单中不显示不需要设置必填
fieldConfig.setIsRequired(false);
}
if (fieldConfig.getShowInQuery()) {
if (Boolean.TRUE.equals(fieldConfig.getShowInQuery())) {
CheckUtils.throwIfNull(fieldConfig.getFormType(), "字段 [{}] 的表单类型不能为空", fieldConfig.getFieldName());
CheckUtils.throwIfNull(fieldConfig.getQueryType(), "字段 [{}] 的查询方式不能为空", fieldConfig.getFieldName());
} else {
@ -182,7 +182,8 @@ public class GeneratorServiceImpl implements GeneratorService {
fieldConfig.setQueryType(null);
}
// 既不在表单也不在查询中显示不需要设置表单类型
if (!fieldConfig.getShowInForm() && !fieldConfig.getShowInQuery()) {
if (Boolean.FALSE.equals(fieldConfig.getShowInForm()) && Boolean.FALSE.equals(fieldConfig
.getShowInQuery())) {
fieldConfig.setFormType(null);
}
fieldConfig.setTableName(tableName);
@ -275,7 +276,7 @@ public class GeneratorServiceImpl implements GeneratorService {
// 2.生成代码
List<GeneratePreviewResp> backendCodePreviewList = generatePreviewList.stream()
.filter(GeneratePreviewResp::isBackend)
.collect(Collectors.toList());
.toList();
Map<String, TemplateConfig> templateConfigMap = generatorProperties.getTemplateConfigs();
for (GeneratePreviewResp codePreview : backendCodePreviewList) {
// 例如D:/continew-admin/continew-admin-tool/src/main/java/top/charles7c/continew/admin/tool/service/impl/XxxServiceImpl.java
@ -298,7 +299,7 @@ public class GeneratorServiceImpl implements GeneratorService {
}
List<GeneratePreviewResp> frontendCodePreviewList = generatePreviewList.stream()
.filter(p -> !p.isBackend())
.collect(Collectors.toList());
.toList();
// 1.生成 api 代码
String apiModuleName = StrUtil.subSuf(packageName, StrUtil
.lastIndexOfIgnoreCase(packageName, StringConstants.DOT) + 1);
@ -342,7 +343,7 @@ public class GeneratorServiceImpl implements GeneratorService {
// 移除需要忽略的字段
List<FieldConfigDO> fieldConfigList = originFieldConfigList.stream()
.filter(fieldConfig -> !StrUtil.equalsAny(fieldConfig.getFieldName(), templateConfig.getExcludeFields()))
.collect(Collectors.toList());
.toList();
genConfigMap.put("fieldConfigs", fieldConfigList);
// 统计部分特殊字段特征
genConfigMap.put("hasLocalDateTime", false);

View File

@ -62,6 +62,8 @@ public class AuthController {
private final LoginService loginService;
private final UserService userService;
private static final String CAPTCHA_EXPIRED = "验证码已失效";
private static final String CAPTCHA_ERROR = "验证码错误";
@SaIgnore
@Operation(summary = "账号登录", description = "根据账号和密码进行登录认证")
@ -69,9 +71,9 @@ public class AuthController {
public R<LoginResp> accountLogin(@Validated @RequestBody AccountLoginReq loginReq) {
String captchaKey = CacheConstants.CAPTCHA_KEY_PREFIX + loginReq.getUuid();
String captcha = RedisUtils.get(captchaKey);
ValidationUtils.throwIfBlank(captcha, "验证码已失效");
ValidationUtils.throwIfBlank(captcha, CAPTCHA_EXPIRED);
RedisUtils.delete(captchaKey);
ValidationUtils.throwIfNotEqualIgnoreCase(loginReq.getCaptcha(), captcha, "验证码错误");
ValidationUtils.throwIfNotEqualIgnoreCase(loginReq.getCaptcha(), captcha, CAPTCHA_ERROR);
// 用户登录
String rawPassword = ExceptionUtils.exToNull(() -> SecureUtils.decryptByRsaPrivateKey(loginReq.getPassword()));
ValidationUtils.throwIfBlank(rawPassword, "密码解密失败");
@ -86,8 +88,8 @@ public class AuthController {
String email = loginReq.getEmail();
String captchaKey = CacheConstants.CAPTCHA_KEY_PREFIX + email;
String captcha = RedisUtils.get(captchaKey);
ValidationUtils.throwIfBlank(captcha, "验证码已失效");
ValidationUtils.throwIfNotEqualIgnoreCase(loginReq.getCaptcha(), captcha, "验证码错误");
ValidationUtils.throwIfBlank(captcha, CAPTCHA_EXPIRED);
ValidationUtils.throwIfNotEqualIgnoreCase(loginReq.getCaptcha(), captcha, CAPTCHA_ERROR);
RedisUtils.delete(captchaKey);
String token = loginService.emailLogin(email);
return R.ok(LoginResp.builder().token(token).build());
@ -100,8 +102,8 @@ public class AuthController {
String phone = loginReq.getPhone();
String captchaKey = CacheConstants.CAPTCHA_KEY_PREFIX + phone;
String captcha = RedisUtils.get(captchaKey);
ValidationUtils.throwIfBlank(captcha, "验证码已失效");
ValidationUtils.throwIfNotEqualIgnoreCase(loginReq.getCaptcha(), captcha, "验证码错误");
ValidationUtils.throwIfBlank(captcha, CAPTCHA_EXPIRED);
ValidationUtils.throwIfNotEqualIgnoreCase(loginReq.getCaptcha(), captcha, CAPTCHA_ERROR);
RedisUtils.delete(captchaKey);
String token = loginService.phoneLogin(phone);
return R.ok(LoginResp.builder().token(token).build());

View File

@ -73,8 +73,8 @@ import java.util.Map;
@RequestMapping("/captcha")
public class CaptchaController {
private final CaptchaService captchaService;
private final Captcha captcha;
private final CaptchaService behaviorCaptchaService;
private final Captcha graphicCaptchaService;
private final ProjectProperties projectProperties;
private final CaptchaProperties captchaProperties;
@ -83,14 +83,14 @@ public class CaptchaController {
@GetMapping("/behavior")
public R<Object> getBehaviorCaptcha(CaptchaVO captchaReq, HttpServletRequest request) {
captchaReq.setBrowserInfo(JakartaServletUtil.getClientIP(request) + request.getHeader(HttpHeaders.USER_AGENT));
return R.ok(captchaService.get(captchaReq).getRepData());
return R.ok(behaviorCaptchaService.get(captchaReq).getRepData());
}
@Log(ignore = true)
@Operation(summary = "校验行为验证码", description = "校验行为验证码")
@PostMapping("/behavior")
public R<Object> checkBehaviorCaptcha(@RequestBody CaptchaVO captchaReq) {
return R.ok(captchaService.check(captchaReq));
return R.ok(behaviorCaptchaService.check(captchaReq));
}
@Log(ignore = true)
@ -99,8 +99,9 @@ public class CaptchaController {
public R<CaptchaResp> getImageCaptcha() {
String uuid = IdUtil.fastUUID();
String captchaKey = CacheConstants.CAPTCHA_KEY_PREFIX + uuid;
RedisUtils.set(captchaKey, captcha.text(), Duration.ofMinutes(captchaProperties.getExpirationInMinutes()));
return R.ok(CaptchaResp.builder().uuid(uuid).img(captcha.toBase64()).build());
RedisUtils.set(captchaKey, graphicCaptchaService.text(), Duration.ofMinutes(captchaProperties
.getExpirationInMinutes()));
return R.ok(CaptchaResp.builder().uuid(uuid).img(graphicCaptchaService.toBase64()).build());
}
@Operation(summary = "获取邮箱验证码", description = "发送验证码到指定邮箱")
@ -133,7 +134,7 @@ public class CaptchaController {
CaptchaVO captchaReq,
HttpServletRequest request) {
// 行为验证码校验
ResponseModel verificationRes = captchaService.verification(captchaReq);
ResponseModel verificationRes = behaviorCaptchaService.verification(captchaReq);
ValidationUtils.throwIfNotEqual(verificationRes.getRepCode(), RepCodeEnum.SUCCESS.getCode(), verificationRes
.getRepMsg());
CaptchaProperties.CaptchaSms captchaSms = captchaProperties.getSms();
@ -143,20 +144,20 @@ public class CaptchaController {
String limitTemplateKeyPrefix = limitKeyPrefix + captchaKeyPrefix;
// 限制短信发送频率
// 1.同一号码同一短信模板1分钟2条1小时8条24小时20条e.g. LIMIT:CAPTCHA:XXX:188xxxxx:1
final String errorMsg = "获取验证码操作太频繁,请稍后再试";
CheckUtils.throwIf(!RedisUtils.rateLimit(RedisUtils
.formatKey(limitTemplateKeyPrefix + "MIN", phone, templateId), RateType.OVERALL, 2, 60), "验证码发送过于频繁,请稍后后再试");
.formatKey(limitTemplateKeyPrefix + "MIN", phone, templateId), RateType.OVERALL, 2, 60), errorMsg);
CheckUtils.throwIf(!RedisUtils.rateLimit(RedisUtils
.formatKey(limitTemplateKeyPrefix + "HOUR", phone, templateId), RateType.OVERALL, 8, 60 * 60), "验证码发送过于频繁,请稍后后再试");
.formatKey(limitTemplateKeyPrefix + "HOUR", phone, templateId), RateType.OVERALL, 8, 60 * 60), errorMsg);
CheckUtils.throwIf(!RedisUtils.rateLimit(RedisUtils
.formatKey(limitTemplateKeyPrefix + "DAY", phone, templateId), RateType.OVERALL, 20, 60 * 60 * 24), "验证码发送过于频繁,请稍后后再试");
.formatKey(limitTemplateKeyPrefix + "DAY", phone, templateId), RateType.OVERALL, 20, 60 * 60 * 24), errorMsg);
// 2.同一号码所有短信模板 24 小时 100 e.g. LIMIT:CAPTCHA:188xxxxx
String limitPhoneKey = limitKeyPrefix + captchaKeyPrefix + phone;
CheckUtils.throwIf(!RedisUtils
.rateLimit(limitPhoneKey, RateType.OVERALL, 100, 60 * 60 * 24), "验证码发送过于频繁,请稍后后再试");
CheckUtils.throwIf(!RedisUtils.rateLimit(limitPhoneKey, RateType.OVERALL, 100, 60 * 60 * 24), errorMsg);
// 3.同一 IP 每分钟限制发送 30 e.g. LIMIT:CAPTCHA:PHONE:1xx.1xx.1xx.1xx
String limitIpKey = RedisUtils.formatKey(limitKeyPrefix + captchaKeyPrefix + "PHONE", JakartaServletUtil
.getClientIP(request));
CheckUtils.throwIf(!RedisUtils.rateLimit(limitIpKey, RateType.OVERALL, 30, 60), "验证码发送过于频繁,请稍后后再试");
CheckUtils.throwIf(!RedisUtils.rateLimit(limitIpKey, RateType.OVERALL, 30, 60), errorMsg);
// 生成验证码
String captcha = RandomUtil.randomNumbers(captchaSms.getLength());
// 发送验证码

View File

@ -44,14 +44,14 @@ import top.charles7c.continew.starter.core.autoconfigure.project.ProjectProperti
import top.charles7c.continew.starter.core.util.validate.ValidationUtils;
import top.charles7c.continew.starter.data.mybatis.plus.base.IBaseEnum;
import top.charles7c.continew.starter.extension.crud.model.query.SortQuery;
import top.charles7c.continew.starter.web.model.R;
import top.charles7c.continew.starter.log.common.annotation.Log;
import top.charles7c.continew.starter.web.model.R;
import java.io.Serializable;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
/**
* 公共 API
@ -108,21 +108,21 @@ public class CommonController {
@CachePenetrationProtect
@CacheRefresh(refresh = 3600, stopRefreshAfterLastAccess = 7200)
@Cached(key = "#code", name = CacheConstants.DICT_KEY_PREFIX)
public R<List<LabelValueResp>> listDict(@PathVariable String code) {
Optional<Class<?>> enumClass = this.getEnumClassByName(code);
return R.ok(enumClass.map(this::listEnumDict).orElseGet(() -> dictItemService.listByDictCode(code)));
public R<List<LabelValueResp<Serializable>>> listDict(@PathVariable String code) {
Optional<Class<?>> enumClassOptional = this.getEnumClassByName(code);
return R.ok(enumClassOptional.map(this::listEnumDict).orElseGet(() -> dictItemService.listByDictCode(code)));
}
@SaIgnore
@Operation(summary = "查询参数", description = "查询参数")
@GetMapping("/option")
@Cached(name = CacheConstants.OPTION_KEY_PREFIX)
public R<List<LabelValueResp>> listOption(@Validated OptionQuery query) {
public R<List<LabelValueResp<String>>> listOption(@Validated OptionQuery query) {
return R.ok(optionService.list(query)
.stream()
.map(option -> new LabelValueResp(option.getCode(), StrUtil.nullToDefault(option.getValue(), option
.map(option -> new LabelValueResp<>(option.getCode(), StrUtil.nullToDefault(option.getValue(), option
.getDefaultValue())))
.collect(Collectors.toList()));
.toList());
}
/**
@ -145,11 +145,11 @@ public class CommonController {
* @param enumClass 枚举类型
* @return 枚举字典
*/
private List<LabelValueResp> listEnumDict(Class<?> enumClass) {
private List<LabelValueResp<Serializable>> listEnumDict(Class<?> enumClass) {
Object[] enumConstants = enumClass.getEnumConstants();
return Arrays.stream(enumConstants).map(e -> {
IBaseEnum<Integer> baseEnum = (IBaseEnum<Integer>)e;
IBaseEnum baseEnum = (IBaseEnum)e;
return new LabelValueResp<>(baseEnum.getDescription(), baseEnum.getValue(), baseEnum.getColor());
}).collect(Collectors.toList());
}).toList();
}
}

View File

@ -51,7 +51,6 @@ import top.charles7c.continew.starter.core.util.validate.ValidationUtils;
import top.charles7c.continew.starter.web.model.R;
import java.util.List;
import java.util.stream.Collectors;
/**
* 个人中心 API
@ -69,6 +68,8 @@ public class UserCenterController {
private final UserService userService;
private final UserSocialService userSocialService;
private final AuthRequestFactory authRequestFactory;
private static final String PASSWORD_DECRYPT_FAILED = "当前密码解密失败";
private static final String CAPTCHA_EXPIRED = "验证码已失效";
@Operation(summary = "上传头像", description = "用户上传个人头像")
@PostMapping("/avatar")
@ -90,7 +91,7 @@ public class UserCenterController {
public R<Void> updatePassword(@Validated @RequestBody UserPasswordUpdateReq updateReq) {
String rawOldPassword = ExceptionUtils.exToNull(() -> SecureUtils.decryptByRsaPrivateKey(updateReq
.getOldPassword()));
ValidationUtils.throwIfNull(rawOldPassword, "当前密码解密失败");
ValidationUtils.throwIfNull(rawOldPassword, PASSWORD_DECRYPT_FAILED);
String rawNewPassword = ExceptionUtils.exToNull(() -> SecureUtils.decryptByRsaPrivateKey(updateReq
.getNewPassword()));
ValidationUtils.throwIfNull(rawNewPassword, "新密码解密失败");
@ -105,10 +106,10 @@ public class UserCenterController {
public R<Void> updatePhone(@Validated @RequestBody UserPhoneUpdateReq updateReq) {
String rawCurrentPassword = ExceptionUtils.exToNull(() -> SecureUtils.decryptByRsaPrivateKey(updateReq
.getCurrentPassword()));
ValidationUtils.throwIfBlank(rawCurrentPassword, "当前密码解密失败");
ValidationUtils.throwIfBlank(rawCurrentPassword, PASSWORD_DECRYPT_FAILED);
String captchaKey = CacheConstants.CAPTCHA_KEY_PREFIX + updateReq.getNewPhone();
String captcha = RedisUtils.get(captchaKey);
ValidationUtils.throwIfBlank(captcha, "验证码已失效");
ValidationUtils.throwIfBlank(captcha, CAPTCHA_EXPIRED);
ValidationUtils.throwIfNotEqualIgnoreCase(updateReq.getCaptcha(), captcha, "验证码错误");
RedisUtils.delete(captchaKey);
userService.updatePhone(updateReq.getNewPhone(), rawCurrentPassword, LoginHelper.getUserId());
@ -120,10 +121,10 @@ public class UserCenterController {
public R<Void> updateEmail(@Validated @RequestBody UserEmailUpdateRequest updateReq) {
String rawCurrentPassword = ExceptionUtils.exToNull(() -> SecureUtils.decryptByRsaPrivateKey(updateReq
.getCurrentPassword()));
ValidationUtils.throwIfBlank(rawCurrentPassword, "当前密码解密失败");
ValidationUtils.throwIfBlank(rawCurrentPassword, PASSWORD_DECRYPT_FAILED);
String captchaKey = CacheConstants.CAPTCHA_KEY_PREFIX + updateReq.getNewEmail();
String captcha = RedisUtils.get(captchaKey);
ValidationUtils.throwIfBlank(captcha, "验证码已失效");
ValidationUtils.throwIfBlank(captcha, CAPTCHA_EXPIRED);
ValidationUtils.throwIfNotEqualIgnoreCase(updateReq.getCaptcha(), captcha, "验证码错误");
RedisUtils.delete(captchaKey);
userService.updateEmail(updateReq.getNewEmail(), rawCurrentPassword, LoginHelper.getUserId());
@ -140,7 +141,7 @@ public class UserCenterController {
userSocialBind.setSource(source);
userSocialBind.setDescription(SocialSourceEnum.valueOf(source).getDescription());
return userSocialBind;
}).collect(Collectors.toList());
}).toList();
return R.ok(userSocialBindList);
}