/**
* 判断用户账号是否被锁定,及超时时间
*/
@Service
@Slf4j
public class LoginService {
@Resource
private RedisTemplate<String, Object> redisTemplate;
private static final int MAX_LOGIN_ATTEMPTS = 5;
private static final String ACCOUNT_PREFIX = "account:";
private static final String LOCKED_KEY_SUFFIX = ":locked";
private static int LOCK_DURATION_MINUTES = 15;
public boolean validateLogin(String username, boolean flag) {
String accountKey = ACCOUNT_PREFIX + username;
String lockedKey = accountKey + LOCKED_KEY_SUFFIX;
if (redisTemplate.hasKey(lockedKey)) {//判断是否存在锁定账号
// 账号已被锁定,获取过期剩余时间
long unlockTimestamp = redisTemplate.getExpire(lockedKey, TimeUnit.SECONDS);
if (unlockTimestamp>0) {
// 还未解锁,拒绝登录
throw exception(AUTH_LOGIN_USER_LOCK,(unlockTimestamp/60));
} else {
// 解锁时间已过,移除锁定状态
redisTemplate.delete(lockedKey);
}
}
if (!flag) {
// 密码错误
Long loginAttempts = redisTemplate.opsForValue().increment(accountKey, 1);
if (loginAttempts >= MAX_LOGIN_ATTEMPTS) {
// 达到锁定阈值,锁定账号
// 设置 key 为 test 的值,并设置超时时间为 15 分钟
redisTemplate.opsForValue().set(lockedKey, lockedKey, LOCK_DURATION_MINUTES, TimeUnit.MINUTES);
}
return false;
} else {
// 密码正确,重置错误计数器
redisTemplate.delete(accountKey);
return true;
}
}
}