xin
2025-06-04 9931d6f56816aecb09333cef2d12777c08793547
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package com.oying.modules.system.service.impl;
 
import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.extra.template.Template;
import cn.hutool.extra.template.TemplateConfig;
import cn.hutool.extra.template.TemplateEngine;
import cn.hutool.extra.template.TemplateUtil;
import com.oying.modules.system.service.VerifyService;
import lombok.RequiredArgsConstructor;
import com.oying.domain.dto.EmailDto;
import com.oying.exception.BadRequestException;
import com.oying.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Collections;
 
/**
 * @author Z
 * @date 2018-12-26
 */
@Service
@RequiredArgsConstructor
public class VerifyServiceImpl implements VerifyService {
 
    @Value("${code.expiration}")
    private Long expiration;
    private final RedisUtils redisUtils;
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public EmailDto sendEmail(String email, String key) {
        EmailDto emailDto;
        String content;
        String redisKey = key + email;
        // 如果不存在有效的验证码,就创建一个新的
        TemplateEngine engine = TemplateUtil.createEngine(new TemplateConfig("template", TemplateConfig.ResourceMode.CLASSPATH));
        Template template = engine.getTemplate("email.ftl");
        String oldCode =  redisUtils.get(redisKey, String.class);
        if(oldCode == null){
            String code = RandomUtil.randomNumbers (6);
            // 存入缓存
            if(!redisUtils.set(redisKey, code, expiration)){
                throw new BadRequestException("服务异常,请联系网站负责人");
            }
            content = template.render(Dict.create().set("code",code));
            // 存在就再次发送原来的验证码
        } else {
            content = template.render(Dict.create().set("code",oldCode));
        }
        emailDto = new EmailDto(Collections.singletonList(email),"OYING 后台管理系统",content);
        return emailDto;
    }
 
    @Override
    public void validated(String key, String code) {
        String value = redisUtils.get(key, String.class);
        if(value == null || !value.equals(code)){
            throw new BadRequestException("无效验证码");
        } else {
            redisUtils.del(key);
        }
    }
}