package com.iplatform.base.captcha; import com.iplatform.base.push.DefaultPushManager; import com.iplatform.base.util.CaptchaUtils; import com.iplatform.base.util.NotificationUtils; import com.iplatform.core.BeanContextAware; import com.walker.cache.CacheProvider; import com.walker.infrastructure.utils.StringUtils; import com.walker.push.Notification; import com.walker.push.PushManager; import com.walker.web.CaptchaProvider; import com.walker.web.CaptchaResult; import com.walker.web.CaptchaType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * 模拟短信的 验证码提供者实现。 * @author 时克英 * @date 2023-01-27 * @date 2023-04-25 重构为正式短信验证提供者,由推送管理器选择短信通道(正式、模拟,根据配置参数来) */ public class SmsCaptchaProvider implements CaptchaProvider { protected final Logger logger = LoggerFactory.getLogger(this.getClass()); @Override public CaptchaResult generateCaptcha(Object param) { if(param == null){ throw new IllegalArgumentException("手机号码必须提供"); } String mobile = param.toString(); if(StringUtils.isEmpty(mobile)){ throw new IllegalArgumentException("手机号码为空,无法发送验证短信"); } // 生成模拟短信验证码(4位数字) String code = StringUtils.generateRandomNumber(4); // 2023-04-25,调用短信推送者 // 由于验证码直接提供的手机号,所以这里目标用户无法取到,只能用手机号。 if(this.pushManager instanceof DefaultPushManager){ ((DefaultPushManager)this.pushManager).pushSmsValidateCode(code, mobile, "creator"); } else { Notification notification = NotificationUtils.acquireSmsValidateCode("templateId", code, mobile, "creator"); // 2023-04-27 验证码不保存数据库 notification.setPersistent(false); this.pushManager.pushSms(notification); } CaptchaResult captchaResult = new CaptchaResult(); captchaResult.setCode(code); captchaResult.setImage(null); return captchaResult; } @Override public boolean validateCaptcha(CaptchaResult data) { CacheProvider captchaCacheProvider = (CacheProvider) BeanContextAware.getBeanByName("captchaCacheProvider"); String smsCodeGenerate = captchaCacheProvider.getCacheData(CaptchaUtils.getVerifyKey(data)); if(StringUtils.isEmpty(smsCodeGenerate)){ logger.error("SmsCaptchaProvider:短信验证信息已失效!"); return false; } if(smsCodeGenerate.equals(data.getCode())){ logger.debug("app验证密码成功,smsCode={}, input={}", smsCodeGenerate, data.getCode()); return true; } return false; } @Override public CaptchaType getCaptchaType() { return CaptchaType.SmsCode; } public void setPushManager(PushManager pushManager) { this.pushManager = pushManager; } private PushManager pushManager; }