1. package me.zhengjie.system.domain;
  2.  
  3. import lombok.AllArgsConstructor;
  4. import lombok.Data;
  5. import lombok.NoArgsConstructor;
  6. import org.hibernate.annotations.CreationTimestamp;
  7.  
  8. import javax.persistence.*;
  9. import javax.validation.constraints.NotBlank;
  10. import java.sql.Timestamp;
  11.  
  12. /**
  13. * @author jie
  14. * @date 2018-12-26
  15. */
  16. @Data
  17. @Entity
  18. @AllArgsConstructor
  19. @NoArgsConstructor
  20. @Table(name = "verification_code")
  21. public class VerificationCode {
  22.  
  23. @Id
  24. @GeneratedValue(strategy = GenerationType.IDENTITY)
  25. private Long id;
  26.  
  27. private String code;
  28.  
  29. /**
  30. * 使用场景,自己定义
  31. */
  32. private String scenes;
  33.  
  34. /**
  35. * true 为有效,false 为无效,验证时状态+时间+具体的邮箱或者手机号
  36. */
  37. private Boolean status = true;
  38.  
  39. /**
  40. * 类型 :phone 和 email
  41. */
  42. @NotBlank
  43. private String type;
  44.  
  45. /**
  46. * 具体的phone与email
  47. */
  48. @NotBlank
  49. private String value;
  50.  
  51. /**
  52. * 创建日期
  53. */
  54. @CreationTimestamp
  55. private Timestamp createTime;
  56.  
  57. public VerificationCode(String code, String scenes, @NotBlank String type, @NotBlank String value) {
  58. this.code = code;
  59. this.scenes = scenes;
  60. this.type = type;
  61. this.value = value;
  62. }
  63. }
  1. package me.zhengjie.system.rest;
  2.  
  3. import me.zhengjie.common.utils.ElAdminConstant;
  4. import me.zhengjie.common.utils.RequestHolder;
  5. import me.zhengjie.core.security.JwtUser;
  6. import me.zhengjie.core.utils.JwtTokenUtil;
  7. import me.zhengjie.system.domain.VerificationCode;
  8. import me.zhengjie.system.service.VerificationCodeService;
  9. import me.zhengjie.tools.domain.vo.EmailVo;
  10. import me.zhengjie.tools.service.EmailService;
  11. import org.springframework.beans.factory.annotation.Autowired;
  12. import org.springframework.beans.factory.annotation.Qualifier;
  13. import org.springframework.http.HttpStatus;
  14. import org.springframework.http.ResponseEntity;
  15. import org.springframework.security.core.userdetails.UserDetailsService;
  16. import org.springframework.web.bind.annotation.*;
  17.  
  18. /**
  19. * @author jie
  20. * @date 2018-12-26
  21. */
  22. @RestController
  23. @RequestMapping("api")
  24. public class VerificationCodeController {
  25.  
  26. @Autowired
  27. private VerificationCodeService verificationCodeService;
  28.  
  29. @Autowired
  30. private JwtTokenUtil jwtTokenUtil;
  31.  
  32. @Autowired
  33. @Qualifier("jwtUserDetailsService")
  34. private UserDetailsService userDetailsService;
  35.  
  36. @Autowired
  37. private EmailService emailService;
  38.  
  39. @PostMapping(value = "/code/resetEmail")
  40. public ResponseEntity resetEmail(@RequestBody VerificationCode code) throws Exception {
  41. code.setScenes(ElAdminConstant.RESET_MAIL);
  42. EmailVo emailVo = verificationCodeService.sendEmail(code);
  43. emailService.send(emailVo,emailService.find());
  44. return new ResponseEntity(HttpStatus.OK);
  45. }
  46.  
  47. @PostMapping(value = "/code/email/resetPass")
  48. public ResponseEntity resetPass() throws Exception {
  49. JwtUser jwtUser = (JwtUser)userDetailsService.loadUserByUsername(jwtTokenUtil.getUserName(RequestHolder.getHttpServletRequest()));
  50. VerificationCode code = new VerificationCode();
  51. code.setType("email");
  52. code.setValue(jwtUser.getEmail());
  53. code.setScenes(ElAdminConstant.RESET_MAIL);
  54. EmailVo emailVo = verificationCodeService.sendEmail(code);
  55. emailService.send(emailVo,emailService.find());
  56. return new ResponseEntity(HttpStatus.OK);
  57. }
  58.  
  59. @GetMapping(value = "/code/validated")
  60. public ResponseEntity validated(VerificationCode code){
  61. verificationCodeService.validated(code);
  62. return new ResponseEntity(HttpStatus.OK);
  63. }
  64. }
  1. package me.zhengjie.system.service;
  2.  
  3. import me.zhengjie.system.domain.VerificationCode;
  4. import me.zhengjie.tools.domain.vo.EmailVo;
  5.  
  6. /**
  7. * @author jie
  8. * @date 2018-12-26
  9. */
  10. public interface VerificationCodeService {
  11.  
  12. /**
  13. * 发送邮件验证码
  14. * @param code
  15. */
  16. EmailVo sendEmail(VerificationCode code);
  17.  
  18. /**
  19. * 验证
  20. * @param code
  21. */
  22. void validated(VerificationCode code);
  23. }
  1. package me.zhengjie.system.service.impl;
  2.  
  3. import cn.hutool.core.util.RandomUtil;
  4. import me.zhengjie.common.exception.BadRequestException;
  5. import me.zhengjie.common.utils.ElAdminConstant;
  6. import me.zhengjie.system.domain.VerificationCode;
  7. import me.zhengjie.system.repository.VerificationCodeRepository;
  8. import me.zhengjie.system.service.VerificationCodeService;
  9. import me.zhengjie.tools.domain.vo.EmailVo;
  10. import org.springframework.beans.factory.annotation.Autowired;
  11. import org.springframework.beans.factory.annotation.Value;
  12. import org.springframework.stereotype.Service;
  13. import org.springframework.transaction.annotation.Propagation;
  14. import org.springframework.transaction.annotation.Transactional;
  15. import java.util.Arrays;
  16. import java.util.concurrent.Executors;
  17. import java.util.concurrent.ScheduledExecutorService;
  18. import java.util.concurrent.TimeUnit;
  19.  
  20. /**
  21. * @author jie
  22. * @date 2018-12-26
  23. */
  24. @Service
  25. @Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
  26. public class VerificationCodeServiceImpl implements VerificationCodeService {
  27.  
  28. @Autowired
  29. private VerificationCodeRepository verificationCodeRepository;
  30.  
  31. @Value("${code.expiration}")
  32. private Integer expiration;
  33.  
  34. @Override
  35. @Transactional(rollbackFor = Exception.class)
  36. public EmailVo sendEmail(VerificationCode code) {
  37. EmailVo emailVo = null;
  38. String content = "";
  39. VerificationCode verificationCode = verificationCodeRepository.findByScenesAndTypeAndValueAndStatusIsTrue(code.getScenes(),code.getType(),code.getValue());
  40. // 如果不存在有效的验证码,就创建一个新的
  41. if(verificationCode == null){
  42. code.setCode(RandomUtil.randomNumbers (6));
  43. content = ElAdminConstant.EMAIL_CODE + code.getCode() + "</p>";
  44. emailVo = new EmailVo(Arrays.asList(code.getValue()),"eladmin后台管理系统",content);
  45. timedDestruction(verificationCodeRepository.save(code));
  46. // 存在就再次发送原来的验证码
  47. } else {
  48. content = ElAdminConstant.EMAIL_CODE + verificationCode.getCode() + "</p>";
  49. emailVo = new EmailVo(Arrays.asList(verificationCode.getValue()),"eladmin后台管理系统",content);
  50. }
  51. return emailVo;
  52. }
  53.  
  54. @Override
  55. public void validated(VerificationCode code) {
  56. VerificationCode verificationCode = verificationCodeRepository.findByScenesAndTypeAndValueAndStatusIsTrue(code.getScenes(),code.getType(),code.getValue());
  57. if(verificationCode == null || !verificationCode.getCode().equals(code.getCode())){
  58. throw new BadRequestException("无效验证码");
  59. } else {
  60. verificationCode.setStatus(false);
  61. verificationCodeRepository.save(verificationCode);
  62. }
  63. }
  64.  
  65. /**
  66. * 定时任务,指定分钟后改变验证码状态
  67. * @param verifyCode
  68. */
  69. private void timedDestruction(VerificationCode verifyCode) {
  70. //以下示例为程序调用结束继续运行
  71. ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
  72. try {
  73. executorService.schedule(() -> {
  74. verifyCode.setStatus(false);
  75. verificationCodeRepository.save(verifyCode);
  76. }, expiration * 60 * 1000L, TimeUnit.MILLISECONDS);
  77. }catch (Exception e){
  78. e.printStackTrace();
  79. }
  80. }
  81. }
  1. package me.zhengjie.system.repository;
  2.  
  3. import me.zhengjie.system.domain.VerificationCode;
  4. import org.springframework.data.jpa.repository.JpaRepository;
  5.  
  6. /**
  7. * @author jie
  8. * @date 2018-12-26
  9. */
  10. public interface VerificationCodeRepository extends JpaRepository<VerificationCode, Long> {
  11.  
  12. /**
  13. * 获取有效的验证码
  14. * @param scenes 业务场景,如重置密码,重置邮箱等等
  15. * @param type
  16. * @param value
  17. * @return
  18. */
  19. VerificationCode findByScenesAndTypeAndValueAndStatusIsTrue(String scenes,String type,String value);
  20. }

VerificationCodeService的更多相关文章

随机推荐

  1. 生成私钥、公钥,配置到Git上

    ssh-keygen -t rsa -C "1032671220@qq.com" 输入完毕指令,输入密码.然后会在 /z/.ssh/文件夹下生成一个私钥rsa_id.公钥rsa_p ...

  2. 基于仿生算法的智能系统I

    仿生算法仿生算法是什么? 什么是仿生? 蜜蜂会造房子,人类就学习蜜蜂盖房子的方法,之后便有了航空建造工程的蜂窝结构. 仿生是模仿生物系统的功能和行为,来建造技术系统的一种科学方法.生活仿生作品现代的飞 ...

  3. golang实现单链表

    package main import "fmt" type Object interface{} type Node struct { data Object next *Nod ...

  4. 干货 | 京东云托管Kubernetes集成镜像仓库并部署原生DashBoard

    在上一篇"Cloud Native 实操系列"文章中,我们为大家介绍了如何通过京东云原生容器实现Eureka的部署(

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

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

  6. Qt5学习笔记(1)-环境配置(win+64bit+VS2013)

    Qt5学习笔记(1)-环境配置 工欲善其事必先-不装-所以装软件 久不露面,赶紧打下酱油. 下载 地址:http://download.qt.io/ 这个小网页就可以下载到跟Qt有关的几乎所有大部分东 ...

  7. cppcheck下载及使用

    一.参考文档 1.Ubuntu下安装Cppcheck源码操作步骤 2.cppcheck std.cfg not found error when std.cfg file is available 3 ...

  8. LeetCode——456.132模式

    给定一个整数序列:a1, a2, ..., an,一个132模式的子序列 ai, aj, ak 被定义为:当 i < j < k 时,ai < ak < aj.设计一个算法,当 ...

  9. Java线程——线程习题(一)子线程执行10次后,主线程再运行5次,这样交替执行三遍

    题目:子线程执行10次后,主线程再运行5次,这样交替执行三遍 代码如下: package com.itheima.gan; /** * 子线程执行10次后,主线程再运行5次,这样交替执行三遍 * @a ...

  10. javaweb学习——会话技术(二)

    文中部分借鉴了:https://www.cnblogs.com/xdp-gacl/p/3855702.html https://blog.csdn.net/p744174529/article/det ...