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

59 lines
1.9 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
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) {
attemptsCache.remove(key);
}
public boolean loginAttemptCheck(String key) {
attemptsCache.compute(
key,
(k, attemptCounter) -> {
if (attemptCounter == null
|| attemptCounter.shouldReset(ATTEMPT_INCREMENT_TIME)) {
return new AttemptCounter();
} else {
attemptCounter.increment();
return attemptCounter;
}
});
return attemptsCache.get(key).getAttemptCount() >= MAX_ATTEMPTS;
}
public boolean isBlocked(String key) {
AttemptCounter attemptCounter = attemptsCache.get(key);
if (attemptCounter != null) {
return attemptCounter.getAttemptCount() >= MAX_ATTEMPTS;
}
return false;
}
}