CaptchaHelper.java 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. package cc.uncarbon.helper;
  2. import cn.hutool.captcha.CaptchaUtil;
  3. import cn.hutool.captcha.ShearCaptcha;
  4. import cn.hutool.core.util.StrUtil;
  5. import lombok.RequiredArgsConstructor;
  6. import org.springframework.data.redis.core.RedisTemplate;
  7. import org.springframework.stereotype.Component;
  8. import java.util.concurrent.TimeUnit;
  9. /**
  10. * 验证码助手类;可将验证码答案缓存至 Redis
  11. *
  12. * @author Uncarbon
  13. */
  14. @Component
  15. @RequiredArgsConstructor
  16. public class CaptchaHelper {
  17. private final RedisTemplate<String, String> stringRedisTemplate;
  18. private static final String CACHE_KEY_CAPTCHA_ANSWER = "Authorization:captcha:uuid_%s";
  19. /**
  20. * 生成一个验证码图片对象
  21. *
  22. * @param uuid UUID
  23. * @return ShearCaptcha
  24. */
  25. public ShearCaptcha generate(String uuid) {
  26. // 定义图形验证码的长、宽、验证码字符数、干扰线宽度
  27. ShearCaptcha captcha = CaptchaUtil.createShearCaptcha(196, 50, 4, 4);
  28. // 将验证码答案保存至 redis , 有效期5分钟
  29. stringRedisTemplate.opsForValue().set(String.format(CACHE_KEY_CAPTCHA_ANSWER, uuid), captcha.getCode(), 300, TimeUnit.SECONDS);
  30. return captcha;
  31. }
  32. /**
  33. * 校验验证码是否输入正确
  34. *
  35. * @param uuid UUID
  36. * @param captchaAnswer 验证码答案
  37. * @param removeWhenEquals 匹配时自动移除缓存键
  38. * @return 是否正确
  39. */
  40. public boolean validate(String uuid, String captchaAnswer, boolean removeWhenEquals) {
  41. if (StrUtil.hasBlank(uuid, captchaAnswer)) {
  42. return false;
  43. }
  44. String cacheKey = String.format(CACHE_KEY_CAPTCHA_ANSWER, uuid);
  45. String answerInRedis = stringRedisTemplate.opsForValue().get(cacheKey);
  46. boolean equals = StrUtil.equalsIgnoreCase(answerInRedis, captchaAnswer);
  47. if (equals && removeWhenEquals) {
  48. stringRedisTemplate.delete(cacheKey);
  49. }
  50. return equals;
  51. }
  52. }