public class SignInRetryLimitService {
private final String lock = "LOCK_RETRY_PWD_USER";
/**
* 登录密码错误重试的次数,没有这个值或值为0表示不限制
*/
@Value("${d1.framework.webapi.signIn.retryCount:5}")
private int retryCount;
/**
* 登录密码错误重试到一定次数后,锁住用户一段时间,单位是分钟
*/
@Value("${d1.framework.webapi.signIn.lockPeriod:60}")
private long lockPeriod;
/**
* 创建一个LoadingCache,并可以进行一些简单的缓存配置
*/
private Cache<String, Integer> retryCache;
public boolean verify(String user, int retryCount) {
if (retryCount <= 0) {
return false;
}
Integer count = getRetryCache().getIfPresent(lock + user);
if (count == null) {
return false;
}
return count >= retryCount;
}
public boolean verifyIsLocked(String user) {
return verify(user, retryCount);
}
public int getWrongCount(String user) {
Integer count = getRetryCache().getIfPresent(lock + user);
if (count == null) {
return 0;
}
return count;
}
public void signInWithWrongPwd(String user) {
if (retryCount <= 0) {
return;
}
Integer count = getRetryCache().getIfPresent(lock + user);
if (count == null) {
count = 0;
}
getRetryCache().put(lock + user, count + 1);
}
public void signInSuccess(String user) {
if (retryCount <= 0) {
return;
}
Integer count = getRetryCache().getIfPresent(lock + user);
if (count == null) {
getRetryCache().invalidate(lock + user);
}
}
//------------------------------------------------------------------------------------
private Cache<String, Integer> getRetryCache() {
if (retryCache == null) {
retryCache = CacheBuilder.newBuilder().expireAfterWrite(lockPeriod, TimeUnit.MINUTES).build();
}
return retryCache;
}
}