中国算力平台算力登记系统2.0
yanzhaofeige
2024-09-30 3c4fee1db116c11d4f04727cfe076d7c94daeaf2
commit | author | age
43dc29 1 package com.odcc.cpzidc.framework.web.service;
Y 2
3 import java.util.concurrent.TimeUnit;
4 import org.springframework.beans.factory.annotation.Autowired;
5 import org.springframework.beans.factory.annotation.Value;
6 import org.springframework.security.core.Authentication;
7 import org.springframework.stereotype.Component;
8 import com.odcc.cpzidc.common.constant.CacheConstants;
9 import com.odcc.cpzidc.common.core.domain.entity.SysUser;
10 import com.odcc.cpzidc.common.core.redis.RedisCache;
11 import com.odcc.cpzidc.common.exception.user.UserPasswordNotMatchException;
12 import com.odcc.cpzidc.common.exception.user.UserPasswordRetryLimitExceedException;
13 import com.odcc.cpzidc.common.utils.SecurityUtils;
14 import com.odcc.cpzidc.framework.security.context.AuthenticationContextHolder;
15
16 /**
17  * 登录密码方法
18  * 
19  * @author ruoyi
20  */
21 @Component
22 public class SysPasswordService
23 {
24     @Autowired
25     private RedisCache redisCache;
26
27     @Value(value = "${user.password.maxRetryCount}")
28     private int maxRetryCount;
29
30     @Value(value = "${user.password.lockTime}")
31     private int lockTime;
32
33     /**
34      * 登录账户密码错误次数缓存键名
35      * 
36      * @param username 用户名
37      * @return 缓存键key
38      */
39     private String getCacheKey(String username)
40     {
41         return CacheConstants.PWD_ERR_CNT_KEY + username;
42     }
43
44     public void validate(SysUser user)
45     {
46         Authentication usernamePasswordAuthenticationToken = AuthenticationContextHolder.getContext();
47         String username = usernamePasswordAuthenticationToken.getName();
48         String password = usernamePasswordAuthenticationToken.getCredentials().toString();
49
50         Integer retryCount = redisCache.getCacheObject(getCacheKey(username));
51
52         if (retryCount == null)
53         {
54             retryCount = 0;
55         }
56
57         if (retryCount >= Integer.valueOf(maxRetryCount).intValue())
58         {
59             throw new UserPasswordRetryLimitExceedException(maxRetryCount, lockTime);
60         }
61
62         if (!matches(user, password))
63         {
64             retryCount = retryCount + 1;
65             redisCache.setCacheObject(getCacheKey(username), retryCount, lockTime, TimeUnit.MINUTES);
66             throw new UserPasswordNotMatchException();
67         }
68         else
69         {
70             clearLoginRecordCache(username);
71         }
72     }
73
74     public boolean matches(SysUser user, String rawPassword)
75     {
76         return SecurityUtils.matchesPassword(rawPassword, user.getPassword());
77     }
78
79     public void clearLoginRecordCache(String loginName)
80     {
81         if (redisCache.hasKey(getCacheKey(loginName)))
82         {
83             redisCache.deleteObject(getCacheKey(loginName));
84         }
85     }
86 }