CaptchaController.java 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135
  1. package com.ruoyi.web.controller;
  2. import cn.dev33.satoken.annotation.SaIgnore;
  3. import cn.hutool.captcha.AbstractCaptcha;
  4. import cn.hutool.captcha.generator.CodeGenerator;
  5. import cn.hutool.core.util.IdUtil;
  6. import cn.hutool.core.util.RandomUtil;
  7. import com.ruoyi.common.core.constant.Constants;
  8. import com.ruoyi.common.core.constant.GlobalConstants;
  9. import com.ruoyi.common.core.domain.R;
  10. import com.ruoyi.common.core.utils.SpringUtils;
  11. import com.ruoyi.common.core.utils.StringUtils;
  12. import com.ruoyi.common.core.utils.reflect.ReflectUtils;
  13. import com.ruoyi.common.mail.config.properties.MailProperties;
  14. import com.ruoyi.common.mail.utils.MailUtils;
  15. import com.ruoyi.common.redis.utils.RedisUtils;
  16. import com.ruoyi.common.sms.config.properties.SmsProperties;
  17. import com.ruoyi.common.sms.core.SmsTemplate;
  18. import com.ruoyi.common.sms.entity.SmsResult;
  19. import com.ruoyi.common.web.config.properties.CaptchaProperties;
  20. import com.ruoyi.common.web.enums.CaptchaType;
  21. import com.ruoyi.web.domain.vo.CaptchaVo;
  22. import jakarta.validation.constraints.NotBlank;
  23. import lombok.RequiredArgsConstructor;
  24. import lombok.extern.slf4j.Slf4j;
  25. import org.springframework.expression.Expression;
  26. import org.springframework.expression.ExpressionParser;
  27. import org.springframework.expression.spel.standard.SpelExpressionParser;
  28. import org.springframework.validation.annotation.Validated;
  29. import org.springframework.web.bind.annotation.GetMapping;
  30. import org.springframework.web.bind.annotation.RestController;
  31. import java.time.Duration;
  32. import java.util.HashMap;
  33. import java.util.Map;
  34. /**
  35. * 验证码操作处理
  36. *
  37. * @author Lion Li
  38. */
  39. @SaIgnore
  40. @Slf4j
  41. @Validated
  42. @RequiredArgsConstructor
  43. @RestController
  44. public class CaptchaController {
  45. private final CaptchaProperties captchaProperties;
  46. private final SmsProperties smsProperties;
  47. private final MailProperties mailProperties;
  48. /**
  49. * 短信验证码
  50. *
  51. * @param phonenumber 用户手机号
  52. */
  53. @GetMapping("/sms/code")
  54. public R<Void> smsCode(@NotBlank(message = "{user.phonenumber.not.blank}") String phonenumber) {
  55. if (!smsProperties.getEnabled()) {
  56. return R.fail("当前系统没有开启短信功能!");
  57. }
  58. String key = GlobalConstants.CAPTCHA_CODE_KEY + phonenumber;
  59. String code = RandomUtil.randomNumbers(4);
  60. RedisUtils.setCacheObject(key, code, Duration.ofMinutes(Constants.CAPTCHA_EXPIRATION));
  61. // 验证码模板id 自行处理 (查数据库或写死均可)
  62. String templateId = "";
  63. Map<String, String> map = new HashMap<>(1);
  64. map.put("code", code);
  65. SmsTemplate smsTemplate = SpringUtils.getBean(SmsTemplate.class);
  66. SmsResult result = smsTemplate.send(phonenumber, templateId, map);
  67. if (!result.isSuccess()) {
  68. log.error("验证码短信发送异常 => {}", result);
  69. return R.fail(result.getMessage());
  70. }
  71. return R.ok();
  72. }
  73. /**
  74. * 邮箱验证码
  75. *
  76. * @param email 邮箱
  77. */
  78. @GetMapping("/email/code")
  79. public R<Void> emailCode(@NotBlank(message = "{user.email.not.blank}") String email) {
  80. if (!mailProperties.getEnabled()) {
  81. return R.fail("当前系统没有开启邮箱功能!");
  82. }
  83. String key = GlobalConstants.CAPTCHA_CODE_KEY + email;
  84. String code = RandomUtil.randomNumbers(4);
  85. RedisUtils.setCacheObject(key, code, Duration.ofMinutes(Constants.CAPTCHA_EXPIRATION));
  86. try {
  87. MailUtils.sendText(email, "登录验证码", "您本次验证码为:" + code + ",有效性为" + Constants.CAPTCHA_EXPIRATION + "分钟,请尽快填写。");
  88. } catch (Exception e) {
  89. log.error("验证码短信发送异常 => {}", e.getMessage());
  90. return R.fail(e.getMessage());
  91. }
  92. return R.ok();
  93. }
  94. /**
  95. * 生成验证码
  96. */
  97. @GetMapping("/code")
  98. public R<CaptchaVo> getCode() {
  99. CaptchaVo captchaVo = new CaptchaVo();
  100. boolean captchaEnabled = captchaProperties.getEnable();
  101. if (!captchaEnabled) {
  102. captchaVo.setCaptchaEnabled(false);
  103. return R.ok(captchaVo);
  104. }
  105. // 保存验证码信息
  106. String uuid = IdUtil.simpleUUID();
  107. String verifyKey = GlobalConstants.CAPTCHA_CODE_KEY + uuid;
  108. // 生成验证码
  109. CaptchaType captchaType = captchaProperties.getType();
  110. boolean isMath = CaptchaType.MATH == captchaType;
  111. Integer length = isMath ? captchaProperties.getNumberLength() : captchaProperties.getCharLength();
  112. CodeGenerator codeGenerator = ReflectUtils.newInstance(captchaType.getClazz(), length);
  113. AbstractCaptcha captcha = SpringUtils.getBean(captchaProperties.getCategory().getClazz());
  114. captcha.setGenerator(codeGenerator);
  115. captcha.createCode();
  116. String code = captcha.getCode();
  117. if (isMath) {
  118. ExpressionParser parser = new SpelExpressionParser();
  119. Expression exp = parser.parseExpression(StringUtils.remove(code, "="));
  120. code = exp.getValue(String.class);
  121. }
  122. RedisUtils.setCacheObject(verifyKey, code, Duration.ofMinutes(Constants.CAPTCHA_EXPIRATION));
  123. captchaVo.setUuid(uuid);
  124. captchaVo.setImg(captcha.getImageBase64());
  125. return R.ok(captchaVo);
  126. }
  127. }