62. Validate user login (#6)
This commit is contained in:
@ -31,7 +31,7 @@ public class GuavaCacheLoginAttemptService implements LoginAttemptService {
|
||||
|
||||
@Override
|
||||
public void loginSucceeded(String username) {
|
||||
loginAttemptsCache.invalidate(username);
|
||||
evictUserFromCache(username);
|
||||
}
|
||||
|
||||
@Override
|
||||
@ -39,6 +39,11 @@ public class GuavaCacheLoginAttemptService implements LoginAttemptService {
|
||||
return getAttempts(username) >= MAX_ATTEMPTS;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void evictUserFromCache(String username) {
|
||||
loginAttemptsCache.invalidate(username);
|
||||
}
|
||||
|
||||
private int getAttempts(String username) {
|
||||
Integer attempts = loginAttemptsCache.getIfPresent(username);
|
||||
return Objects.requireNonNullElse(attempts, 0);
|
||||
|
||||
@ -2,8 +2,8 @@ package net.shyshkin.study.fullstack.supportportal.backend.service;
|
||||
|
||||
public interface LoginAttemptService {
|
||||
|
||||
static final int MAX_ATTEMPTS = 5;
|
||||
static final int ATTEMPT_INCREMENT = 1;
|
||||
int MAX_ATTEMPTS = 5;
|
||||
int ATTEMPT_INCREMENT = 1;
|
||||
|
||||
void loginFailed(String username);
|
||||
|
||||
@ -11,4 +11,5 @@ public interface LoginAttemptService {
|
||||
|
||||
boolean hasExceededMaxAttempts(String username);
|
||||
|
||||
void evictUserFromCache(String username);
|
||||
}
|
||||
|
||||
@ -36,6 +36,7 @@ public class UserServiceImpl implements UserService {
|
||||
|
||||
private final UserRepository userRepository;
|
||||
private final PasswordEncoder passwordEncoder;
|
||||
private final LoginAttemptService loginAttemptService;
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
@ -43,11 +44,21 @@ public class UserServiceImpl implements UserService {
|
||||
User user = userRepository
|
||||
.findByUsername(username)
|
||||
.orElseThrow(() -> new UsernameNotFoundException(String.format(USERNAME_NOT_FOUND_MSG, username)));
|
||||
validateLoginAttempts(user);
|
||||
user.setLastLoginDateDisplay(user.getLastLoginDate());
|
||||
user.setLastLoginDate(LocalDateTime.now());
|
||||
return new UserPrincipal(user);
|
||||
}
|
||||
|
||||
private void validateLoginAttempts(User user) {
|
||||
if (user.isNotLocked()) {
|
||||
if (loginAttemptService.hasExceededMaxAttempts(user.getUsername()))
|
||||
user.setNotLocked(false);
|
||||
} else {
|
||||
loginAttemptService.evictUserFromCache(user.getUsername());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public User register(String firstName, String lastName, String username, String email) {
|
||||
|
||||
|
||||
Reference in New Issue
Block a user