CaptchaController.java 5.3 KB

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