package com.izouma.nineth.service; import com.izouma.nineth.dto.Captcha; import com.wf.captcha.SpecCaptcha; import lombok.AllArgsConstructor; import org.apache.commons.lang3.StringUtils; import org.ehcache.UserManagedCache; import org.ehcache.config.builders.ExpiryPolicyBuilder; import org.ehcache.config.builders.UserManagedCacheBuilder; import org.springframework.stereotype.Service; import java.awt.*; import java.io.IOException; import java.time.Duration; import java.util.UUID; @Service @AllArgsConstructor public class CaptchaService { private final UserManagedCache captchaCache = UserManagedCacheBuilder.newUserManagedCacheBuilder(String.class, String.class) .withExpiry(ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofMinutes(10))) .build(true); public Captcha gen() throws IOException, FontFormatException { String key = UUID.randomUUID().toString(); SpecCaptcha specCaptcha = new SpecCaptcha(90 * 2, 32 * 2, 5); specCaptcha.setFont(com.wf.captcha.base.Captcha.FONT_7, 24 * 2); String code = specCaptcha.text().toLowerCase(); String image = specCaptcha.toBase64(); captchaCache.put(key, code); return new Captcha(key, image); } public boolean verify(String key, String code) { if (StringUtils.isBlank(key) || StringUtils.isBlank(code)) { return false; } code = code.toLowerCase(); boolean verify = false; String trueCode = captchaCache.get(key); if (StringUtils.isNotBlank(trueCode) && trueCode.equals(code)) { verify = true; } return verify; } }