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
|
|
|
|
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
|
|
|
|
2023-12-29 20:48:21 +00:00
|
|
|
private int MAX_ATTEMPTS;
|
|
|
|
private long ATTEMPT_INCREMENT_TIME;
|
2023-12-30 19:11:27 +00:00
|
|
|
|
2023-12-29 20:48:21 +00:00
|
|
|
@PostConstruct
|
|
|
|
public void init() {
|
|
|
|
MAX_ATTEMPTS = applicationProperties.getSecurity().getLoginAttemptCount();
|
|
|
|
ATTEMPT_INCREMENT_TIME =
|
|
|
|
TimeUnit.MINUTES.toMillis(
|
|
|
|
applicationProperties.getSecurity().getLoginResetTimeMinutes());
|
|
|
|
}
|
2023-12-30 19:11:27 +00:00
|
|
|
|
2023-12-24 17:12:32 +00:00
|
|
|
private final ConcurrentHashMap<String, AttemptCounter> attemptsCache =
|
|
|
|
new ConcurrentHashMap<>();
|
|
|
|
|
|
|
|
public void loginSucceeded(String key) {
|
2024-05-12 19:58:34 +02:00
|
|
|
attemptsCache.remove(key.toLowerCase());
|
2023-12-24 17:12:32 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
public boolean loginAttemptCheck(String key) {
|
2024-05-12 19:58:34 +02:00
|
|
|
return attemptsCache
|
|
|
|
.compute(
|
|
|
|
key.toLowerCase(),
|
|
|
|
(k, attemptCounter) -> {
|
|
|
|
if (attemptCounter == null
|
|
|
|
|| attemptCounter.shouldReset(ATTEMPT_INCREMENT_TIME)) {
|
|
|
|
return new AttemptCounter();
|
|
|
|
} else {
|
|
|
|
attemptCounter.increment();
|
|
|
|
return attemptCounter;
|
|
|
|
}
|
|
|
|
})
|
|
|
|
.getAttemptCount()
|
|
|
|
>= MAX_ATTEMPTS;
|
2023-12-24 17:12:32 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
public boolean isBlocked(String key) {
|
2024-05-12 19:58:34 +02:00
|
|
|
AttemptCounter attemptCounter = attemptsCache.get(key.toLowerCase());
|
2023-12-24 17:12:32 +00:00
|
|
|
if (attemptCounter != null) {
|
2024-05-12 19:58:34 +02:00
|
|
|
return attemptCounter.getAttemptCount() >= MAX_ATTEMPTS
|
|
|
|
&& !attemptCounter.shouldReset(ATTEMPT_INCREMENT_TIME);
|
2023-12-24 17:12:32 +00:00
|
|
|
}
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
}
|