refactor: 优化部分代码

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

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);
}