001package run.iget.framework.captcha.service.impl; 002 003import org.springframework.stereotype.Service; 004 005import com.wf.captcha.SpecCaptcha; 006import com.wf.captcha.base.Captcha; 007 008import cn.hutool.cache.impl.TimedCache; 009import cn.hutool.core.util.IdUtil; 010import cn.hutool.core.util.StrUtil; 011import lombok.extern.slf4j.Slf4j; 012import run.iget.framework.captcha.req.CaptchaReq; 013import run.iget.framework.captcha.resp.CaptchaResp; 014import run.iget.framework.captcha.service.CaptchaService; 015import run.iget.framework.common.enums.BaseResultEnum; 016import run.iget.framework.common.util.ExceptionThrowUtils; 017 018@Slf4j 019@Service 020public class CaptchaServiceImpl implements CaptchaService { 021 022 private static final TimedCache<String, String> CAPTCHA_TIMED_CACHE = new TimedCache<>(TIME_OUT); 023 024 static { 025 CAPTCHA_TIMED_CACHE.schedulePrune(1000); 026 } 027 028 @Override 029 public CaptchaResp generate() { 030 // 生成base64验证码 031 SpecCaptcha captcha = new SpecCaptcha(150, 40); 032 captcha.setLen(5); 033 captcha.setCharType(Captcha.TYPE_DEFAULT); 034 String text = captcha.text(); 035 // 生成key 036 String key = IdUtil.fastSimpleUUID(); 037 // 封装返回数据 038 CaptchaResp resp = new CaptchaResp(); 039 resp.setKey(key); 040 resp.setImage(captcha.toBase64()); 041 042 log.info("key: {}, captcha: {}", key, text); 043 044 CAPTCHA_TIMED_CACHE.put(resp.getKey(), text); 045 return resp; 046 } 047 048 @Override 049 public void verify(CaptchaReq captchaReq) { 050 String key = captchaReq.getKey(); 051 ExceptionThrowUtils.ofTrue(StrUtil.hasBlank(key, captchaReq.getCaptcha()), BaseResultEnum.ERROR_CAPTCHA); 052 String cache = CAPTCHA_TIMED_CACHE.get(captchaReq.getKey(), false); 053 ExceptionThrowUtils.ofTrue(!StrUtil.equals(cache, captchaReq.getCaptcha(), true), BaseResultEnum.ERROR_CAPTCHA); 054 CAPTCHA_TIMED_CACHE.remove(captchaReq.getKey()); 055 } 056 057}