package me.zhengjie.system.domain;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.hibernate.annotations.CreationTimestamp; import javax.persistence.*;
import javax.validation.constraints.NotBlank;
import java.sql.Timestamp; /**
* @author jie
* @date 2018-12-26
*/
@Data
@Entity
@AllArgsConstructor
@NoArgsConstructor
@Table(name = "verification_code")
public class VerificationCode { @Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id; private String code; /**
* 使用场景,自己定义
*/
private String scenes; /**
* true 为有效,false 为无效,验证时状态+时间+具体的邮箱或者手机号
*/
private Boolean status = true; /**
* 类型 :phone 和 email
*/
@NotBlank
private String type; /**
* 具体的phone与email
*/
@NotBlank
private String value; /**
* 创建日期
*/
@CreationTimestamp
private Timestamp createTime; public VerificationCode(String code, String scenes, @NotBlank String type, @NotBlank String value) {
this.code = code;
this.scenes = scenes;
this.type = type;
this.value = value;
}
}
package me.zhengjie.system.rest;

import me.zhengjie.common.utils.ElAdminConstant;
import me.zhengjie.common.utils.RequestHolder;
import me.zhengjie.core.security.JwtUser;
import me.zhengjie.core.utils.JwtTokenUtil;
import me.zhengjie.system.domain.VerificationCode;
import me.zhengjie.system.service.VerificationCodeService;
import me.zhengjie.tools.domain.vo.EmailVo;
import me.zhengjie.tools.service.EmailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.web.bind.annotation.*; /**
* @author jie
* @date 2018-12-26
*/
@RestController
@RequestMapping("api")
public class VerificationCodeController { @Autowired
private VerificationCodeService verificationCodeService; @Autowired
private JwtTokenUtil jwtTokenUtil; @Autowired
@Qualifier("jwtUserDetailsService")
private UserDetailsService userDetailsService; @Autowired
private EmailService emailService; @PostMapping(value = "/code/resetEmail")
public ResponseEntity resetEmail(@RequestBody VerificationCode code) throws Exception {
code.setScenes(ElAdminConstant.RESET_MAIL);
EmailVo emailVo = verificationCodeService.sendEmail(code);
emailService.send(emailVo,emailService.find());
return new ResponseEntity(HttpStatus.OK);
} @PostMapping(value = "/code/email/resetPass")
public ResponseEntity resetPass() throws Exception {
JwtUser jwtUser = (JwtUser)userDetailsService.loadUserByUsername(jwtTokenUtil.getUserName(RequestHolder.getHttpServletRequest()));
VerificationCode code = new VerificationCode();
code.setType("email");
code.setValue(jwtUser.getEmail());
code.setScenes(ElAdminConstant.RESET_MAIL);
EmailVo emailVo = verificationCodeService.sendEmail(code);
emailService.send(emailVo,emailService.find());
return new ResponseEntity(HttpStatus.OK);
} @GetMapping(value = "/code/validated")
public ResponseEntity validated(VerificationCode code){
verificationCodeService.validated(code);
return new ResponseEntity(HttpStatus.OK);
}
}
package me.zhengjie.system.service;

import me.zhengjie.system.domain.VerificationCode;
import me.zhengjie.tools.domain.vo.EmailVo; /**
* @author jie
* @date 2018-12-26
*/
public interface VerificationCodeService { /**
* 发送邮件验证码
* @param code
*/
EmailVo sendEmail(VerificationCode code); /**
* 验证
* @param code
*/
void validated(VerificationCode code);
}
package me.zhengjie.system.service.impl;

import cn.hutool.core.util.RandomUtil;
import me.zhengjie.common.exception.BadRequestException;
import me.zhengjie.common.utils.ElAdminConstant;
import me.zhengjie.system.domain.VerificationCode;
import me.zhengjie.system.repository.VerificationCodeRepository;
import me.zhengjie.system.service.VerificationCodeService;
import me.zhengjie.tools.domain.vo.EmailVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.util.Arrays;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit; /**
* @author jie
* @date 2018-12-26
*/
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class VerificationCodeServiceImpl implements VerificationCodeService { @Autowired
private VerificationCodeRepository verificationCodeRepository; @Value("${code.expiration}")
private Integer expiration; @Override
@Transactional(rollbackFor = Exception.class)
public EmailVo sendEmail(VerificationCode code) {
EmailVo emailVo = null;
String content = "";
VerificationCode verificationCode = verificationCodeRepository.findByScenesAndTypeAndValueAndStatusIsTrue(code.getScenes(),code.getType(),code.getValue());
// 如果不存在有效的验证码,就创建一个新的
if(verificationCode == null){
code.setCode(RandomUtil.randomNumbers (6));
content = ElAdminConstant.EMAIL_CODE + code.getCode() + "</p>";
emailVo = new EmailVo(Arrays.asList(code.getValue()),"eladmin后台管理系统",content);
timedDestruction(verificationCodeRepository.save(code));
// 存在就再次发送原来的验证码
} else {
content = ElAdminConstant.EMAIL_CODE + verificationCode.getCode() + "</p>";
emailVo = new EmailVo(Arrays.asList(verificationCode.getValue()),"eladmin后台管理系统",content);
}
return emailVo;
} @Override
public void validated(VerificationCode code) {
VerificationCode verificationCode = verificationCodeRepository.findByScenesAndTypeAndValueAndStatusIsTrue(code.getScenes(),code.getType(),code.getValue());
if(verificationCode == null || !verificationCode.getCode().equals(code.getCode())){
throw new BadRequestException("无效验证码");
} else {
verificationCode.setStatus(false);
verificationCodeRepository.save(verificationCode);
}
} /**
* 定时任务,指定分钟后改变验证码状态
* @param verifyCode
*/
private void timedDestruction(VerificationCode verifyCode) {
//以下示例为程序调用结束继续运行
ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
try {
executorService.schedule(() -> {
verifyCode.setStatus(false);
verificationCodeRepository.save(verifyCode);
}, expiration * 60 * 1000L, TimeUnit.MILLISECONDS);
}catch (Exception e){
e.printStackTrace();
}
}
}
package me.zhengjie.system.repository;

import me.zhengjie.system.domain.VerificationCode;
import org.springframework.data.jpa.repository.JpaRepository; /**
* @author jie
* @date 2018-12-26
*/
public interface VerificationCodeRepository extends JpaRepository<VerificationCode, Long> { /**
* 获取有效的验证码
* @param scenes 业务场景,如重置密码,重置邮箱等等
* @param type
* @param value
* @return
*/
VerificationCode findByScenesAndTypeAndValueAndStatusIsTrue(String scenes,String type,String value);
}

VerificationCodeService的更多相关文章

随机推荐

  1. SAP_SD常用事务代码

    1.创建/修改/显示销售订单:VA01/VA02/VA03 2.根据销售订单创建交货单:VL01N 3.修改/显示交货单:VL02N/VL03N 4.交货单发货过账:VL02N 5.发货过账冲销:VL ...

  2. 新iPhone泄密12人被捕,苹果这是下狠手的节奏

    一直以来,苹果在保密这件事儿上就秉持着强硬态度.还记得当年乔老爷子在的时候,苹果的保密工作在科技行业算得上是首屈一指.每款iPhone及其他新品在正式发布前,几乎不会被曝出什么消息.而这,或许也是&q ...

  3. 杂点-shell

    使用while循环读取文件 cat file.txt |while read line do echo $line done 或者: while read line do echo $line don ...

  4. zabbix监控一个机器上的多个java进程的jvm

    一.监控安装部署 1.1 JVM端口配置 (/bqhexin/tomcat/bin/catalina.sh)在安装的tomcat路径,找到catalina.sh文件. vim编辑并添加: catali ...

  5. Vue.js(15)之 json-server搭建模拟的API服务器

    json-server搭建模拟的API服务器 运行命令 npm install json-server -D 全局安装 json-server 项目根目录下创建 mock 文件夹 mock 文件夹下添 ...

  6. javascript函数柯里化初探

    // 柯里化之前 function add(x,y,z){ return x+y+z; } add(1,2,3) // 6 // 柯里化之后 function curryAdd(x){ return ...

  7. Mybatis实现if trim(四)

    1. 准备 请先完成Mybatis实现增删改查(二)和Mybatis实现条件查询(三)的基本内容 2. 关于多条件查询的疑问 在Mybatis实现条件查询(三)中我们实现了多条件(商品编码.商品名称. ...

  8. Thread--两线程交替打印

    package t3.copy; public class ThreadA extends Thread { private Object lock; public ThreadA(Object lo ...

  9. 自动生成返回Json数据的toString()方法

    平时书写实体类方法的时候,想要获取的值直接返回Json字符串,以便使用,可以直接在Eclipse里面生成. 实现步骤: 1.快捷键Alt+S 2.选择Edit 3.添加字段,名称随意(我的为JsonS ...

  10. 冲刺期末阶段一<公文档案流转管理系统>

    今天下午的四节课要求自己完成公文流转管理系统,并规定时间看个人进程,相对来说我对增删改查掌握的不彻底,对项目的逻辑框架不太熟练,所以我感觉今天的进度有点慢.有待继续学习. 完成进度:1.分步骤先理清整 ...