获取验证码 及登陆登出

pull/3/head
caolin 2023-08-13 00:19:00 +08:00
parent 456a6192f6
commit 15462ce0ba
8 changed files with 105 additions and 12 deletions

View File

@ -32,7 +32,6 @@ public class SwaggerConfig {
@Order(value = 1) @Order(value = 1)
public Docket adminDocket(){ public Docket adminDocket(){
return new Docket(DocumentationType.SWAGGER_2) return new Docket(DocumentationType.SWAGGER_2)
.pathMapping("/driver-api")
.enable(true) .enable(true)
.apiInfo(groupApiInfo()) .apiInfo(groupApiInfo())
.select() .select()

View File

@ -6,5 +6,8 @@ package com.jwl.driver.server.constant;
public class Constants { public class Constants {
public static String MESSAGE_CODE_PREFIX = "code_";
public static String MESSAGE_TEMPLATE = "SMS_198880447";
} }

View File

@ -12,6 +12,7 @@ import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;
import javax.validation.Valid;
import java.time.LocalDateTime; import java.time.LocalDateTime;
/** /**
@ -31,10 +32,17 @@ public class TdSysUserController {
@Autowired @Autowired
private ITdSysUserService userService; private ITdSysUserService userService;
@ApiOperation("用户登陆")
@GetMapping("/code")
public BaseResponse code(@RequestParam String phone) {
log.info("获取验证码======>phone:{}", phone);
return BaseResponse.success(userService.code(phone));
}
@ApiOperation("用户登陆") @ApiOperation("用户登陆")
@PostMapping("/login") @PostMapping("/login")
public BaseResponse login(@RequestBody LoginUserDto loginUserDto) { public BaseResponse login(@RequestBody @Valid LoginUserDto loginUserDto) {
log.info("用户登录======>loginUserDto:{}", loginUserDto); log.info("用户登录======>loginUserDto:{}", loginUserDto);
return BaseResponse.success(userService.login(loginUserDto)); return BaseResponse.success(userService.login(loginUserDto));
} }

View File

@ -1,6 +1,7 @@
package com.jwl.driver.server.exception; package com.jwl.driver.server.exception;
import com.jwl.driver.server.enums.StatusEnum;
import com.jwl.driver.server.response.BaseResponse; import com.jwl.driver.server.response.BaseResponse;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -44,4 +45,9 @@ public class GlobalExceptionHandler {
public BaseResponse<?> signatureException(SignatureException e) { public BaseResponse<?> signatureException(SignatureException e) {
return BaseResponse.fail("E004", "token is invalid"); return BaseResponse.fail("E004", "token is invalid");
} }
@ExceptionHandler(Exception.class)
public BaseResponse<?> exception(Exception e) {
return BaseResponse.fail(StatusEnum.FAIL.getCode(), null, null);
}
} }

View File

@ -15,6 +15,13 @@ import com.jwl.driver.server.vo.LoginUserVo;
*/ */
public interface ITdSysUserService extends IService<TdSysUser> { public interface ITdSysUserService extends IService<TdSysUser> {
/**
*
* @param phone
* @return
*/
String code(String phone);
/** /**
* *
* @param loginUserDto * @param loginUserDto
@ -27,4 +34,5 @@ public interface ITdSysUserService extends IService<TdSysUser> {
* @return * @return
*/ */
Boolean loginOut(); Boolean loginOut();
} }

View File

@ -1,7 +1,9 @@
package com.jwl.driver.server.service.impl; package com.jwl.driver.server.service.impl;
import cn.hutool.core.util.PhoneUtil;
import cn.hutool.core.util.StrUtil; import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jwl.driver.server.constant.Constants;
import com.jwl.driver.server.dto.LoginUserDto; import com.jwl.driver.server.dto.LoginUserDto;
import com.jwl.driver.server.entity.TdSysUser; import com.jwl.driver.server.entity.TdSysUser;
import com.jwl.driver.server.exception.BusinessException; import com.jwl.driver.server.exception.BusinessException;
@ -9,15 +11,18 @@ import com.jwl.driver.server.mapper.TdSysUserMapper;
import com.jwl.driver.server.redis.RedisCache; import com.jwl.driver.server.redis.RedisCache;
import com.jwl.driver.server.service.ITdSysUserService; import com.jwl.driver.server.service.ITdSysUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jwl.driver.server.util.SmsUtil;
import com.jwl.driver.server.util.TokenThreadUtil; import com.jwl.driver.server.util.TokenThreadUtil;
import com.jwl.driver.server.vo.LoginUserVo; import com.jwl.driver.server.vo.LoginUserVo;
import org.springframework.beans.BeanUtils; import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.util.UUID; import java.util.UUID;
import java.util.concurrent.TimeUnit;
/** /**
* <p> * <p>
@ -33,15 +38,48 @@ public class TdSysUserServiceImpl extends ServiceImpl<TdSysUserMapper, TdSysUser
@Autowired @Autowired
private RedisCache redisCache; private RedisCache redisCache;
@Value("${token.expireTime}")
private Integer tokenExpireTime;
@Value("${message.code.expireTime}")
private Integer codeExpireTime;
@Override
public String code(String phone) {
if (!PhoneUtil.isPhone(phone)) {
throw new BusinessException("手机号格式不正确");
}
if (redisCache.hasKey(Constants.MESSAGE_CODE_PREFIX + phone)){
Long expire = redisCache.getExpire(Constants.MESSAGE_CODE_PREFIX + phone);
throw new BusinessException("请在" + expire + "秒后重新获取验证码");
}
String code = SmsUtil.sendMessage(phone);
redisCache.setCacheObject((Constants.MESSAGE_CODE_PREFIX + phone), code, codeExpireTime, TimeUnit.SECONDS);
return code;
}
@Override @Override
@Transactional(rollbackFor = Exception.class) @Transactional(rollbackFor = Exception.class)
public LoginUserVo login(LoginUserDto loginUserDto) { public LoginUserVo login(LoginUserDto loginUserDto) {
//todo 这里还需要校验验证码 //校验验证码
String code = redisCache.getCacheObject(Constants.MESSAGE_CODE_PREFIX + loginUserDto.getPhone());
if (StrUtil.isBlank(code)){
throw new BusinessException("验证码已过期,请重新获取");
}
if (!StrUtil.equals(code,loginUserDto.getCode())){
throw new BusinessException("验证码错误");
}
LambdaQueryWrapper<TdSysUser> cond = new LambdaQueryWrapper<TdSysUser>() LambdaQueryWrapper<TdSysUser> cond = new LambdaQueryWrapper<TdSysUser>()
.eq(TdSysUser::getPhone, "18255439337"); .eq(TdSysUser::getPhone, "18255439337");
//用户不存在则直接注册登陆 //用户不存在则直接注册登陆
TdSysUser tdSysUser = this.baseMapper.selectOne(cond); TdSysUser tdSysUser = this.baseMapper.selectOne(cond);
//todo 用户基础信息填写这里还要完善一下
if (tdSysUser == null) { if (tdSysUser == null) {
tdSysUser = new TdSysUser() tdSysUser = new TdSysUser()
.setUserName("车友") .setUserName("车友")
@ -55,11 +93,11 @@ public class TdSysUserServiceImpl extends ServiceImpl<TdSysUserMapper, TdSysUser
} }
String token = UUID.randomUUID().toString(); String token = UUID.randomUUID().toString();
redisCache.setCacheObject(token,"123456",365*24*60*60);
LoginUserVo loginUserVo = new LoginUserVo(); LoginUserVo loginUserVo = new LoginUserVo();
BeanUtils.copyProperties(tdSysUser, loginUserVo); BeanUtils.copyProperties(tdSysUser, loginUserVo);
loginUserVo.setToken(token); loginUserVo.setToken(token);
// 存入redis
redisCache.setCacheObject(token, tdSysUser, tokenExpireTime, TimeUnit.DAYS);
return loginUserVo; return loginUserVo;
} }
@ -71,4 +109,5 @@ public class TdSysUserServiceImpl extends ServiceImpl<TdSysUserMapper, TdSysUser
} }
return Boolean.TRUE; return Boolean.TRUE;
} }
} }

View File

@ -8,6 +8,9 @@ import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException; import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile; import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile; import com.aliyuncs.profile.IClientProfile;
import com.jwl.driver.server.constant.Constants;
import com.jwl.driver.server.exception.BusinessException;
import jdk.vm.ci.meta.Constant;
import lombok.Data; import lombok.Data;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -37,6 +40,21 @@ public class SmsUtil {
//用于存储短信验证码 //用于存储短信验证码
private static Map<String, String> codeMap = new HashMap<>(); private static Map<String, String> codeMap = new HashMap<>();
/**
*
* @param sendPhone
* @return
*/
public static String sendMessage(String sendPhone) {
String code = getMessageCode(sendPhone);
Map<String, Object> param = new HashMap<>();
param.put("code", code);
//发送短信
currencySendMessage(sendPhone, Constants.MESSAGE_TEMPLATE, JSONObject.toJSONString(param));
return code;
}
/** /**
* *
*/ */
@ -87,12 +105,14 @@ public class SmsUtil {
} catch (ClientException e) { } catch (ClientException e) {
logger.error("发送短信失败:"+e.getErrMsg()+"\n"+e.getMessage()); logger.error("发送短信失败:"+e.getErrMsg()+"\n"+e.getMessage());
e.printStackTrace(); e.printStackTrace();
throw new BusinessException("获取验证码失败");
} }
if (sendSmsResponse!=null){ if (sendSmsResponse!=null){
logger.info("message:"+sendSmsResponse.getMessage()+"\n"+ logger.info("message:"+sendSmsResponse.getMessage()+"\n"+
"code:"+sendSmsResponse.getCode()+"\n"); "code:"+sendSmsResponse.getCode()+"\n");
}else{ }else{
logger.info("发送短信响应为null"); logger.info("发送短信响应为null");
throw new BusinessException("获取验证码失败");
} }
return JSONObject.toJSONString(sendSmsResponse); return JSONObject.toJSONString(sendSmsResponse);
@ -117,8 +137,8 @@ public class SmsUtil {
public static void main(String[] args) throws IOException { public static void main(String[] args) throws IOException {
Map<String, Object> param = new HashMap<>(); Map<String, Object> param = new HashMap<>();
param.put("code", getMessageCode("18855146869")); param.put("code", getMessageCode("18255439337"));
SmsUtil.currencySendMessage("18855146869", "SMS_198880447", JSONObject.toJSONString(param) ); SmsUtil.currencySendMessage("18255439337", "SMS_198880447", JSONObject.toJSONString(param) );
} }
} }

View File

@ -41,6 +41,16 @@ driver:
- /driver-api/v2/api-docs - /driver-api/v2/api-docs
- /driver-api/swagger-resources - /driver-api/swagger-resources
- /driver-api/favicon.ico - /driver-api/favicon.ico
- /driver-api/tdSysUser/code
# 需要权限校验url集合 # 需要权限校验url集合
needAuthEndPoints: needAuthEndPoints:
# token 有效期1年
token:
expireTime: 365
# 短信验证码失效时间5分钟
message:
code:
expireTime: 300