Browse Source

登录获取验证码以及验证码的配置

master
dimengzhe 2 years ago
parent
commit
9fbfae5486
  1. 105
      mallplus-mbg/src/main/java/com/zscat/mallplus/enums/SmsEnum.java
  2. 4
      mallplus-mbg/src/main/java/com/zscat/mallplus/ums/mapper/SmsDao.java
  3. 21
      mallplus-portal/pom.xml
  4. 8
      mallplus-portal/src/main/java/com/zscat/mallplus/b2c/BHomeController.java
  5. 51
      mallplus-portal/src/main/java/com/zscat/mallplus/config/SmsConfig.java
  6. 30
      mallplus-portal/src/main/java/com/zscat/mallplus/single/SingelHomeController.java
  7. 3
      mallplus-portal/src/main/java/com/zscat/mallplus/ums/service/IUmsMemberService.java
  8. 9
      mallplus-portal/src/main/java/com/zscat/mallplus/ums/service/RedisService.java
  9. 20
      mallplus-portal/src/main/java/com/zscat/mallplus/ums/service/impl/RedisServiceImpl.java
  10. 7
      mallplus-portal/src/main/java/com/zscat/mallplus/ums/service/impl/SmsServiceImpl.java
  11. 61
      mallplus-portal/src/main/java/com/zscat/mallplus/ums/service/impl/UmsMemberServiceImpl.java

105
mallplus-mbg/src/main/java/com/zscat/mallplus/enums/SmsEnum.java

@ -0,0 +1,105 @@
package com.zscat.mallplus.enums;
import lombok.Getter;
/**
* @Author dimengzhe
* @Date 2023/2/23 9:01
* @Description
*/
public class SmsEnum {
/**
* 手机短信登录验证码时效()
*/
public static final Long APP_LOGIN_CODE_TIME_LIMIT = 300L;
/**
* 发送验证码
*/
@Getter
public static enum SendEnum {
/**
* 登录
*/
LOGIN("1", "loginCode","登录"),
;
/**
* code值
*/
private final String code;
/**
* 备注
*/
private final String remarks;
/**
* 缓存识别码
*/
private final String redisKey;
/**
* 构造器
*
* @param code code值
* @param redisKey 缓存识别码
* @param remarks 备注
*/
private SendEnum(String code, String redisKey,String remarks) {
this.code = code;
this.remarks = remarks;
this.redisKey = redisKey;
}
}
@Getter
public static enum SmsReturnEnum {
/**
* 发送短信返回参数
*/
ZERO("1", "提交成功"),
ONE("-1", "账号未注册"),
TWO("-2", "网络访问超时,请稍后再试"),
three("-3", "帐号或密码错误"),
FOUR("-4", "只支持单发"),
FIVE("-5", "余额不足,请充值"),
SIX("-6", "定时发送时间不是有效的时间格式"),
SEVEN("-7", "提交信息末尾未加签名,请添加中文的企业签名【 】或未采用gb2312编码"),
EIGHT("-8", "发送内容需在1到300字之间"),
NINE("-9", "发送号码为空"),
TEN("-10", "定时时间不能小于系统当前时间"),
ELEVEN("-11", "屏蔽手机号码"),
ONEZEROONE("-101", "调用接口速度太快"),
;
/**
* code值
*/
private final String code;
/**
* 备注
*/
private final String remarks;
/**
* 构造器
*
* @param code code值
* @param remarks 备注
*/
private SmsReturnEnum(String code, String remarks) {
this.code = code;
this.remarks = remarks;
}
public static String getValueByKey(String code) {
SmsReturnEnum[] sysReturnEnum = values();
for (SmsReturnEnum returnEnum: sysReturnEnum) {
if (returnEnum.getCode().equals(code)) {
return returnEnum.getRemarks();
}
}
return null;
}
}
}

4
mallplus-mbg/src/main/java/com/zscat/mallplus/ums/mapper/SmsDao.java

@ -25,8 +25,8 @@ import java.util.Map;
public interface SmsDao {
@Options(useGeneratedKeys = true, keyProperty = "id")
@Insert("insert into sys_sms(phone, signName, templateCode, params, day, createTime, updateTime) "
+ "values(#{phone}, #{signName}, #{templateCode}, #{params}, #{day}, #{createTime}, #{updateTime})")
@Insert("insert into sys_sms(phone, signName, templateCode, params, day, createTime, updateTime,bizId,code,message) "
+ "values(#{phone}, #{signName}, #{templateCode}, #{params}, #{day}, #{createTime}, #{updateTime},#{bizId},#{code},#{message})")
int save(Sms sms);
@Select("select * from sys_sms t where t.id = #{id}")

21
mallplus-portal/pom.xml

@ -183,6 +183,27 @@
<artifactId>okhttp</artifactId>
<version>3.14.4</version>
</dependency>
<!--发送短信-->
<dependency>
<groupId>org.apache.axis</groupId>
<artifactId>axis</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>axis</groupId>
<artifactId>axis-jaxrpc</artifactId>
<version>1.2.1</version>
</dependency>
<dependency>
<groupId>commons-discovery</groupId>
<artifactId>commons-discovery</artifactId>
<version>0.2</version>
</dependency>
<dependency>
<groupId>wsdl4j</groupId>
<artifactId>wsdl4j</artifactId>
<version>1.6.3</version>
</dependency>
</dependencies>
<build>

8
mallplus-portal/src/main/java/com/zscat/mallplus/b2c/BHomeController.java

@ -6,6 +6,7 @@ import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zscat.mallplus.annotation.IgnoreAuth;
import com.zscat.mallplus.annotation.SysLog;
import com.zscat.mallplus.cms.entity.CmsSubject;
import com.zscat.mallplus.enums.SmsEnum;
import com.zscat.mallplus.oms.service.IOmsOrderService;
import com.zscat.mallplus.oms.vo.HomeContentResult;
import com.zscat.mallplus.pms.entity.PmsProduct;
@ -38,6 +39,7 @@ import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.AuthenticationException;
@ -390,13 +392,13 @@ public class BHomeController {
@IgnoreAuth
@ApiOperation("获取验证码")
@PostMapping(value = "/user.sms")
public Object sendSmsCode(@RequestParam String phone) {
public Object sendSmsCode(@RequestParam("phone") String phone,@RequestParam(value = "type",required = false)String type) {
try {
if (!PhoneUtil.checkPhone(phone)) {
throw new IllegalArgumentException("手机号格式不正确");
}
SmsCode smsCode = memberService.generateCode(phone);
Date date = new Date();
SmsCode smsCode = memberService.generateCode(phone,type,date);
return new CommonResult().success(smsCode);
} catch (Exception e) {
e.printStackTrace();

51
mallplus-portal/src/main/java/com/zscat/mallplus/config/SmsConfig.java

@ -0,0 +1,51 @@
package com.zscat.mallplus.config;
import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.axis.encoding.XMLType;
import javax.xml.namespace.QName;
/**
* @Author dimengzhe
* @Date 2023/2/22 21:38
* @Description
*/
public class SmsConfig {
static String msgSign="【汇融银链】";
public static String SendWaitWorkMsg(String mobile, String pwd,String msg) {
try {
String urlname = "http://sdk1.mb345.com/ws/LinkWS.asmx";
String soapActionURI = "http://tempuri.org/BatchSend";
Service s = new Service();
Call call = (Call) s.createCall();
call.setTimeout(new Integer(5000));
call.setUseSOAPAction(true);
call.setSOAPActionURI(soapActionURI);
// wsdl中接口名称
call.setOperationName(new QName("http://tempuri.org/", "BatchSend"));
call.setTargetEndpointAddress(urlname);
call.addParameter(new QName("http://tempuri.org/", "CorpID"), XMLType.XSD_STRING,
javax.xml.rpc.ParameterMode.IN);
call.addParameter(new QName("http://tempuri.org/", "Pwd"), XMLType.XSD_STRING,
javax.xml.rpc.ParameterMode.IN);
call.addParameter(new QName("http://tempuri.org/", "Mobile"), XMLType.XSD_STRING,
javax.xml.rpc.ParameterMode.IN);
call.addParameter(new QName("http://tempuri.org/", "Content"), XMLType.XSD_STRING,
javax.xml.rpc.ParameterMode.IN);
call.addParameter(new QName("http://tempuri.org/", "Cell"), XMLType.XSD_STRING,
javax.xml.rpc.ParameterMode.IN);
call.addParameter(new QName("http://tempuri.org/", "SendTime"), XMLType.XSD_STRING,
javax.xml.rpc.ParameterMode.IN);
String[] fn01 = {"YXT011836", "yxt_hryl230223", mobile, msg+msgSign, "", ""};
String val = (String) call.invoke(fn01);
return val;
} catch (Exception e) {
return e.getMessage();
}
}
}

30
mallplus-portal/src/main/java/com/zscat/mallplus/single/SingelHomeController.java

@ -6,6 +6,7 @@ import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zscat.mallplus.annotation.IgnoreAuth;
import com.zscat.mallplus.annotation.SysLog;
import com.zscat.mallplus.config.MallplusProperties;
import com.zscat.mallplus.enums.SmsEnum;
import com.zscat.mallplus.exception.Server;
import com.zscat.mallplus.oms.service.IOmsOrderService;
import com.zscat.mallplus.oms.vo.HomeContentResult;
@ -35,6 +36,7 @@ import com.zscat.mallplus.vo.UmsMemberInfoDetail;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.AuthenticationException;
@ -338,8 +340,9 @@ public class SingelHomeController {
@IgnoreAuth
@ApiOperation(value = "手机号 密码登录")
@PostMapping(value = "/login")
public Object login(@RequestParam String phone,
@RequestParam String password) {
public Object login(@RequestParam("phone") String phone,
@RequestParam("password") String password,
@RequestParam(value = "type",required = false)String type) {
if (phone == null || "".equals(phone)) {
return new CommonResult().validateFailed("用户名或密码错误");
}
@ -347,7 +350,6 @@ public class SingelHomeController {
return new CommonResult().validateFailed("用户名或密码错误");
}
try {
Map<String, Object> token = memberService.login(phone, password);
if (token.get("token") == null) {
log.info("用户名或密码错误");
@ -441,12 +443,30 @@ public class SingelHomeController {
@IgnoreAuth
@ApiOperation("获取验证码")
@PostMapping(value = "/sms/codes")
public Object sendSmsCode(@RequestParam String phone) {
public Object sendSmsCode(@RequestParam("phone") String phone,@RequestParam("type")String type) {
try {
if (!PhoneUtil.checkPhone(phone)) {
throw new IllegalArgumentException("手机号格式不正确");
}
SmsCode smsCode = memberService.generateCode(phone);
if(StringUtils.isBlank(type)){
return new CommonResult().failed("参数错误:type");
}
//缓存识别码
String redisKey = "";
if(SmsEnum.SendEnum.LOGIN.getCode().equals(type)){
redisKey = SmsEnum.SendEnum.LOGIN.getRedisKey();
}
Date date = new Date();
String codeRedis = redisService.get(redisKey + phone);
if (StringUtils.isNotEmpty(codeRedis)) {
//查看请求间隔,默认是一分钟,小于一分钟继续等待,超过一分钟发送短信
String sendTime = codeRedis.substring(4);
long diffSecond = (date.getTime() - Long.parseLong(sendTime)) / 1000;
if (diffSecond < 60) {
return new CommonResult().failed("请等待一分钟后再次重试!");
}
}
SmsCode smsCode = memberService.generateCode(phone,type,date);
return new CommonResult().success(smsCode);
} catch (Exception e) {

3
mallplus-portal/src/main/java/com/zscat/mallplus/ums/service/IUmsMemberService.java

@ -10,6 +10,7 @@ import com.zscat.mallplus.vo.AppletLoginnewParam;
import com.zscat.mallplus.vo.SmsCode;
import org.springframework.transaction.annotation.Transactional;
import java.util.Date;
import java.util.Map;
/**
@ -90,7 +91,7 @@ public interface IUmsMemberService extends IService<UmsMember> {
Object register(UmsMember umsMember);
SmsCode generateCode(String phone);
SmsCode generateCode(String phone, String type, Date date);
Map<String, Object> loginByCode(String phone, String authCode);

9
mallplus-portal/src/main/java/com/zscat/mallplus/ums/service/RedisService.java

@ -33,5 +33,14 @@ public interface RedisService {
*/
Long increment(String key, long delta);
/**
* 写入缓存设置时效时间
* @param key
* @param value
* @param expireTime
* @return
*/
boolean set(final String key, Object value, Long expireTime);
}

20
mallplus-portal/src/main/java/com/zscat/mallplus/ums/service/impl/RedisServiceImpl.java

@ -3,9 +3,12 @@ package com.zscat.mallplus.ums.service.impl;
import com.zscat.mallplus.ums.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import java.io.Serializable;
import java.util.concurrent.TimeUnit;
/**
@ -17,6 +20,9 @@ public class RedisServiceImpl implements RedisService {
@Autowired
private StringRedisTemplate stringRedisTemplate;
@Autowired
private RedisTemplate redisTemplate;
@Override
public void set(String key, String value) {
stringRedisTemplate.opsForValue().set(key, value);
@ -41,4 +47,18 @@ public class RedisServiceImpl implements RedisService {
public Long increment(String key, long delta) {
return stringRedisTemplate.opsForValue().increment(key, delta);
}
@Override
public boolean set(String key, Object value, Long expireTime) {
boolean result = false;
try {
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
operations.set(key, value);
stringRedisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
}

7
mallplus-portal/src/main/java/com/zscat/mallplus/ums/service/impl/SmsServiceImpl.java

@ -6,6 +6,7 @@ import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.zscat.mallplus.config.SmsConfig;
import com.zscat.mallplus.ums.entity.Sms;
import com.zscat.mallplus.ums.mapper.SmsDao;
import com.zscat.mallplus.ums.service.SmsService;
@ -82,11 +83,10 @@ public class SmsServiceImpl implements SmsService {
}
// 测试时不需要开此 add by someday end
update(sms);
return response;
}
@Transactional
@Transactional(rollbackFor = Exception.class)
@Override
public void save(Sms sms, Map<String, String> params) {
if (!CollectionUtils.isEmpty(params)) {
@ -96,7 +96,8 @@ public class SmsServiceImpl implements SmsService {
sms.setCreateTime(new Date());
sms.setUpdateTime(sms.getCreateTime());
sms.setDay(sms.getCreateTime());
sms.setBizId(sms.getBizId());
sms.setMessage(sms.getMessage());
smsDao.save(sms);
}

61
mallplus-portal/src/main/java/com/zscat/mallplus/ums/service/impl/UmsMemberServiceImpl.java

@ -4,7 +4,9 @@ import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.Gson;
import com.zscat.mallplus.config.MallplusProperties;
import com.zscat.mallplus.config.SmsConfig;
import com.zscat.mallplus.enums.AllEnum;
import com.zscat.mallplus.enums.SmsEnum;
import com.zscat.mallplus.exception.ApiMallPlusException;
import com.zscat.mallplus.oms.mapper.OmsOrderMapper;
import com.zscat.mallplus.oms.vo.OrderStstic;
@ -24,6 +26,7 @@ import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
@ -44,7 +47,6 @@ import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
@ -412,25 +414,19 @@ public class UmsMemberServiceImpl extends ServiceImpl<UmsMemberMapper, UmsMember
}
@Override
public SmsCode generateCode(String phone) {
public SmsCode generateCode(String phone,String type,Date date) {
//生成流水号
String uuid = UUID.randomUUID().toString();
StringBuilder sb = new StringBuilder();
Random random = new Random();
for (int i = 0; i < 6; i++) {
for (int i = 0; i < 4; i++) {
sb.append(random.nextInt(10));
}
Map<String, String> map = new HashMap<>(2);
map.put("code", sb.toString());
map.put("phone", phone);
//短信验证码缓存15分钟,
redisService.set(REDIS_KEY_PREFIX_AUTH_CODE + phone, sb.toString());
redisService.expire(REDIS_KEY_PREFIX_AUTH_CODE + phone, expireMinute * 60);
//存储sys_sms
saveSmsAndSendCode(phone, sb.toString());
saveSmsAndSendCode(phone, sb.toString(),type,date);
SmsCode smsCode = new SmsCode();
smsCode.setKey(uuid);
return smsCode;
@ -442,33 +438,36 @@ public class UmsMemberServiceImpl extends ServiceImpl<UmsMemberMapper, UmsMember
* @param phone
* @param code
*/
private void saveSmsAndSendCode(String phone, String code) {
checkTodaySendCount(phone);
private void saveSmsAndSendCode(String phone, String code, String type, Date date) {
Sms sms = new Sms();
sms.setPhone(phone);
sms.setParams(code);
Map<String, String> params = new HashMap<>();
params.put("code", code);
String content = "";
String redisKey = "";
if (SmsEnum.SendEnum.LOGIN.getCode().equals(type)) {
content = "验证码:" + code + ",用于登录App,有效期5分钟,如非本人操作,请忽略该短信。";
redisKey = SmsEnum.SendEnum.LOGIN.getRedisKey();
}
String result = SmsConfig.SendWaitWorkMsg(phone, code, content);
if ("1".equals(result)) {
//返回的信息
String resultMsg = SmsEnum.SmsReturnEnum.getValueByKey(result);
sms.setCode(sms.getCode());
sms.setBizId(result);//返回的code
sms.setMessage(resultMsg);
redisService.set(redisKey + phone, code + date.getTime(), SmsEnum.APP_LOGIN_CODE_TIME_LIMIT);
log.info("发送短信结果:code:{},message:{}, 1,发送成功");
}else{
//返回的信息
String resultMsg = SmsEnum.SmsReturnEnum.getValueByKey(result);
sms.setBizId(result);//返回的code
//返回的信息
sms.setMessage(resultMsg);
LOGGER.error("发送短信失败:{}", resultMsg);
}
smsService.save(sms, params);
//异步调用阿里短信接口发送短信
CompletableFuture.runAsync(() -> {
try {
smsService.sendSmsMsg(sms);
} catch (Exception e) {
params.put("err", e.getMessage());
smsService.save(sms, params);
e.printStackTrace();
LOGGER.error("发送短信失败:{}", e.getMessage());
}
});
// 当天发送验证码次数+1
String countKey = countKey(phone);
redisService.increment(countKey, 1L);
redisService.expire(countKey, 1 * 3600 * 24);
}
/**

Loading…
Cancel
Save