Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

78 lines
2.5 KiB
Java
Raw Normal View History

2023-12-24 17:12:32 +00:00
package stirling.software.SPDF.config.security;
2023-12-30 19:11:27 +00:00
2023-12-24 17:12:32 +00:00
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
2023-12-24 17:56:31 +00:00
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
2023-12-29 20:48:21 +00:00
import org.springframework.beans.factory.annotation.Autowired;
2023-12-24 17:56:31 +00:00
import org.springframework.stereotype.Service;
2023-12-29 20:48:21 +00:00
import jakarta.annotation.PostConstruct;
import stirling.software.SPDF.model.ApplicationProperties;
2023-12-24 17:12:32 +00:00
import stirling.software.SPDF.model.AttemptCounter;
@Service
public class LoginAttemptService {
2023-12-29 20:48:21 +00:00
@Autowired ApplicationProperties applicationProperties;
2023-12-30 19:11:27 +00:00
private static final Logger logger = LoggerFactory.getLogger(LoginAttemptService.class);
private int MAX_ATTEMPT;
2023-12-29 20:48:21 +00:00
private long ATTEMPT_INCREMENT_TIME;
private ConcurrentHashMap<String, AttemptCounter> attemptsCache;
2023-12-30 19:11:27 +00:00
2023-12-29 20:48:21 +00:00
@PostConstruct
public void init() {
MAX_ATTEMPT = applicationProperties.getSecurity().getLoginAttemptCount();
2023-12-29 20:48:21 +00:00
ATTEMPT_INCREMENT_TIME =
TimeUnit.MINUTES.toMillis(
applicationProperties.getSecurity().getLoginResetTimeMinutes());
attemptsCache = new ConcurrentHashMap<>();
2023-12-29 20:48:21 +00:00
}
2023-12-30 19:11:27 +00:00
2023-12-24 17:12:32 +00:00
public void loginSucceeded(String key) {
if (key == null || key.trim().isEmpty()) {
return;
}
attemptsCache.remove(key.toLowerCase());
2023-12-24 17:12:32 +00:00
}
public void loginFailed(String key) {
if (key == null || key.trim().isEmpty()) return;
AttemptCounter attemptCounter = attemptsCache.get(key.toLowerCase());
if (attemptCounter == null) {
attemptCounter = new AttemptCounter();
attemptsCache.put(key.toLowerCase(), attemptCounter);
} else {
if (attemptCounter.shouldReset(ATTEMPT_INCREMENT_TIME)) {
attemptCounter.reset();
}
attemptCounter.increment();
}
2023-12-24 17:12:32 +00:00
}
public boolean isBlocked(String key) {
if (key == null || key.trim().isEmpty()) return false;
AttemptCounter attemptCounter = attemptsCache.get(key.toLowerCase());
if (attemptCounter == null) {
return false;
2023-12-24 17:12:32 +00:00
}
return attemptCounter.getAttemptCount() >= MAX_ATTEMPT;
}
public int getRemainingAttempts(String key) {
if (key == null || key.trim().isEmpty()) return MAX_ATTEMPT;
AttemptCounter attemptCounter = attemptsCache.get(key.toLowerCase());
if (attemptCounter == null) {
return MAX_ATTEMPT;
}
return MAX_ATTEMPT - attemptCounter.getAttemptCount();
2023-12-24 17:12:32 +00:00
}
}