Redis 实现 用户输入密码错误5次锁定

/**

* 判断用户账号是否被锁定,及超时时间

*/

@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;

}

}

}

相关推荐
欧哈东哥9 分钟前
【C++】标准库中用于组合多个值的数据结构pair、tuple、array...
java·数据结构·c++
python_13613 分钟前
web请求和响应
java·spring·github
柏油30 分钟前
可视化 MySQL binlog 监听方案
数据库·后端·mysql
k↑1 小时前
微服务之注册中心与ShardingSphere关于分库分表的那些事
数据库·微服务·架构·shardingsphere
ciku2 小时前
Spring AI Starter和文档解读
java·人工智能·spring
柏油2 小时前
MySQL 字符集 utf8 与 utf8mb4
数据库·后端·mysql
程序猿阿越2 小时前
Kafka源码(三)发送消息-客户端
java·后端·源码阅读
我科绝伦(Huanhuan Zhou)2 小时前
异构数据库兼容力测评:KingbaseES 与 MySQL 的语法・功能・性能全场景验证解析
数据库·mysql