CaptchaService.java 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. package com.izouma.nineth.service;
  2. import com.izouma.nineth.dto.Captcha;
  3. import com.wf.captcha.SpecCaptcha;
  4. import lombok.AllArgsConstructor;
  5. import org.apache.commons.lang3.StringUtils;
  6. import org.ehcache.UserManagedCache;
  7. import org.ehcache.config.builders.ExpiryPolicyBuilder;
  8. import org.ehcache.config.builders.UserManagedCacheBuilder;
  9. import org.springframework.stereotype.Service;
  10. import java.awt.*;
  11. import java.io.IOException;
  12. import java.time.Duration;
  13. import java.util.UUID;
  14. @Service
  15. @AllArgsConstructor
  16. public class CaptchaService {
  17. private final UserManagedCache<String, String> captchaCache =
  18. UserManagedCacheBuilder.newUserManagedCacheBuilder(String.class, String.class)
  19. .withExpiry(ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofMinutes(10)))
  20. .build(true);
  21. public Captcha gen() throws IOException, FontFormatException {
  22. String key = UUID.randomUUID().toString();
  23. SpecCaptcha specCaptcha = new SpecCaptcha(90 * 2, 32 * 2, 5);
  24. specCaptcha.setFont(com.wf.captcha.base.Captcha.FONT_7, 24 * 2);
  25. String code = specCaptcha.text().toLowerCase();
  26. String image = specCaptcha.toBase64();
  27. captchaCache.put(key, code);
  28. return new Captcha(key, image);
  29. }
  30. public boolean verify(String key, String code) {
  31. if (StringUtils.isBlank(key) || StringUtils.isBlank(code)) {
  32. return false;
  33. }
  34. code = code.toLowerCase();
  35. boolean verify = false;
  36. String trueCode = captchaCache.get(key);
  37. if (StringUtils.isNotBlank(trueCode) && trueCode.equals(code)) {
  38. verify = true;
  39. }
  40. return verify;
  41. }
  42. }