kongzy
2024-09-14 f0f00e9ba8a755e4317e029d73b69a92ad9f9df1
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
package com.gkhy.exam.framework.web.service;
 
import com.gkhy.exam.common.constant.CacheConstant;
import com.gkhy.exam.common.constant.Constant;
import com.gkhy.exam.common.domain.entity.SysUser;
import com.gkhy.exam.common.exception.ApiException;
import com.gkhy.exam.common.utils.RedisUtils;
import com.gkhy.exam.common.utils.SecurityUtils;
import com.gkhy.exam.framework.manager.AsyncManager;
import com.gkhy.exam.framework.manager.factory.AsyncFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
 
import java.util.concurrent.TimeUnit;
 
@Component
public class SysPasswordService {
 
    @Autowired
    private RedisUtils redisUtils;
 
 
    @Value(value = "${user.password.maxRetryCount:5}")
    private Integer maxRetryCount;
 
    @Value(value = "${user.password.lockTime:10}")
    private int lockTime;
 
    /**
     * 登录账户密码错误次数缓存键名
     *
     * @param username 用户名
     * @return 缓存键key
     */
    private String getCacheKey(String username)
    {
        return CacheConstant.PWD_ERR_CNT_KEY + username;
    }
 
    public void validate(SysUser user,String password)  {
        String username=user.getUsername();
        String key= redisUtils.generateKey(getCacheKey(username));
        Integer retryCount= (Integer) redisUtils.get(key);
        if(retryCount==null){
            retryCount=0;
        }
        if(retryCount>maxRetryCount){
            AsyncManager.me().execute(AsyncFactory.recordLoginInfo(username, Constant.LOGIN_FAIL,"密码输入错误5次,帐户锁定"+lockTime+"分钟"));
            throw new ApiException("密码输入错误5次,帐户锁定5分钟");
        }
        if(!matches(user,password)){
            retryCount=retryCount+1;
            AsyncManager.me().execute(AsyncFactory.recordLoginInfo(username, Constant.LOGIN_FAIL,String.format("密码输入错误%d次",retryCount)));
            redisUtils.set(key,retryCount,lockTime, TimeUnit.MINUTES);//5分钟后释放
            throw new ApiException("密码不匹配");
        }else{
            redisUtils.del(key);
        }
 
    }
 
    public boolean matches(SysUser sysUser,String rawPassword){
        return SecurityUtils.matchesPassword(rawPassword,sysUser.getPassword());
    }
}