无关风月
2024-07-04 941caf616bded8ff1faa0a0875f2f37a11d9913d
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
66
67
68
69
70
71
72
package com.ruoyi.management.service.impl;
 
import cn.hutool.core.util.RandomUtil;
import com.ruoyi.common.core.constant.Constants;
import com.ruoyi.common.core.constant.RedisConstants;
import com.ruoyi.common.core.exception.GlobalException;
import com.ruoyi.management.domain.TUser;
import com.ruoyi.management.mapper.TUserMapper;
import com.ruoyi.management.service.ITUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.management.utils.HWSendSms;
import com.ruoyi.study.api.dto.AppUserQuery;
import com.ruoyi.study.api.vo.AppUserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
 
import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;
 
/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author 无关风月
 * @since 2024-04-26
 */
@Service
public class TUserServiceImpl extends ServiceImpl<TUserMapper, TUser> implements ITUserService {
    @Resource
    private RedisTemplate<String, Object> redisTemplate;
//    @Override
//    public List<AppUserVO> listAll(AppUserQuery query) {
//        return this.baseMapper.listAll(query);
//    }
@Autowired
private HWSendSms hwSendSms;
    @Override
    public Boolean phoneCode(String phone) throws Exception {
        // 生成随机 6位数字 验证码
        String phoneCode = RandomUtil.randomNumbers(6);
 
        hwSendSms.sendSms(phoneCode, phone);
        // 判断redis中是否存在手机验证码
        Object phoneCodeRedis = redisTemplate.opsForValue().get(RedisConstants.PHONE_CODE + phone);
        if (phoneCodeRedis == null) {
            // 将手机验证码 key: reg:用户输入的手机号码  value: 随机验证码:时间戳
            phoneCodeRedis = phoneCode;
        } else {
            // redis有验证码,获取redis中value的时间戳,判断是否过期
            long oldTime = Long.parseLong(String.valueOf(phoneCodeRedis).split(":")[1]);
            // 没有超过1分钟的重发时间
            if (System.currentTimeMillis() - oldTime < (long) Constants.SIXTY * Constants.ONE_THOUSAND) {
                throw new GlobalException("操作频繁,稍后重试!!!");
            } else {
                phoneCode = String.valueOf(phoneCodeRedis).split(":")[0];
            }
        }
        /*
         * 保存信息到redis
         * key为 --> phone_code:手机号码 (phone_code表示该业务为 验证码登录)
         * value为 --> 随机验证码:时间戳 (时间戳用于计算是否超过1分钟的重发时间)
         */
        redisTemplate.opsForValue().set(RedisConstants.PHONE_CODE + phone, phoneCode + ":" + System.currentTimeMillis(), 5, TimeUnit.MINUTES);
        String sendMessage = "验证码发送成功,您的验证码为:" + phoneCode + ",该验证码三分钟内有效,请及时完成登陆";
        // todo 发送此消息
        System.out.println(sendMessage);
        return true;
    }
}