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. 1, vm: PropTypes.instanceOf(VM).isRequired

    子模块的文件引入父工程对象时,出现红色warning,提示传入的对象类型不是所要求的类型. 思路是父工程引用的JS包和子模块使用的包不是同一个包,解决办法是父工程和子工程都使用同一个包. resolv ...

  2. 用户使用API函数对创建的文件进行读写操作

    HANDLE handle; //定义文件句柄 ]; //定义缓冲区 int i; //接收实际操作的字节数 CString str; //定义字符串变量 handle = ::CreateFile( ...

  3. h5-transform-3d

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  4. SQL基础教程(第2版)第4章 数据更新:4-4 事务

    ●事务是需要在同一个处理单元中执行的一系列更新处理的集合. ● 事务处理的终止指令包括COMMIT(提交处理)和ROLLBACK(取消处理)两种. ● DBMS的事务具有原子性(Atomicity). ...

  5. python刷LeetCode:5. 最长回文子串

    难度等级:中等 题目描述: 给定一个字符串 s,找到 s 中最长的回文子串.你可以假设 s 的最大长度为 1000. 示例 1: 输入: "babad"输出: "bab& ...

  6. CodeForces-1100C NN and the Optical Illusion 简单数学

    题目链接:https://vjudge.net/problem/CodeForces-1100C 题意: 题目给出外部圆的数目n和内部圆的半径r,要求求出外部圆的半径以满足图片要求. 显然这是一道数学 ...

  7. rename 修改文件名

    Linux的 rename 命令有两个版本,一个是C语言版本的,一个是Perl语言版本的,早期的Linux发行版基本上使用的是C语言版本的,现在已经很难见到C语言版本的了,由于历史原因,在Perl语言 ...

  8. leetcode 994.腐烂的橘子

    题目: 在给定的网格中,每个单元格可以有以下三个值之一: 值 0 代表空单元格: 值 1 代表新鲜橘子: 值 2 代表腐烂的橘子. 每分钟,任何与腐烂的橘子(在 4 个正方向上)相邻的新鲜橘子都会腐烂 ...

  9. Python笔记_第四篇_高阶编程_进程、线程、协程_4.协程

    1.协程的概念: 子程序或者子函数,在所有语言中都是层级调用,比如A调用B,再B执行的过程中又可以调用C,C执行完毕返回,B执行返回,最后是A执行完毕返回.是通过栈来实现的,一个线程就是执行一个自称, ...

  10. 浅谈对RabbitMQ的认识

    一.什么是消息队列?什么时候使用它? 在传统的web架构中(此处特指Java SSM架构),用户在web中进行了某项需要和后台产生交互的操作后,一般都要开启一个session,从view层开始,由co ...