puzhibing
2023-10-08 22199bbdda579861736420fe26c2873ab0f5d21c
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
package com.sinata.rest.modular.system.service.impl;
 
import com.sinata.rest.common.lock.IdLocker;
import com.sinata.rest.core.util.MD5Util;
import com.sinata.rest.modular.system.service.RedisTemplateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
 
@Component
public class AuthService {
 
    @Autowired
    private RedisTemplateService redis;
 
    private IdLocker locker = new IdLocker();
 
    public long createCheckCode(String type, String randomKey, Integer userId, String showId, String id) {
        final long timeStamp = System.currentTimeMillis();
        locker.locked(userId, () -> {
            String codeKey = "" + userId + type + id;
            String code = redis.stringGetStringByKey(codeKey);
            if (StringUtils.isEmpty(code)) {
                code = createCode(timeStamp, type, randomKey, userId.toString(), showId, id);
//                System.out.println("签名key = " + codeKey);
//                System.out.println("签名code = " + code);
//                System.out.println("时间戳 = " + timeStamp);
                redis.stringSetValueAndExpireTime(codeKey, code, 1000 * 60);
            }
        });
        return timeStamp;
    }
 
    public boolean checkCode(Integer userId, String type, Integer id, String code) {
        return code.equals(redis.stringGetStringByKey("" + userId + type + id));
    }
 
    private String createCode(Long time, String type, String randomKey, String userId, String showId, String id) {
        long remain = time / (1000 * 60) % 36;
        String str = MD5Util.encrypt(new StringBuilder().append(type).append(randomKey).append(userId).append(showId).append(id).toString());
        for (int i = 0; i < (int) remain; i++) {
            str = MD5Util.encrypt(str + i);
        }
        return str;
    }
 
}