2023-08-13 01:14:30 +01:00
|
|
|
package stirling.software.SPDF.config.security;
|
|
|
|
|
|
|
|
import java.util.Collection;
|
|
|
|
import java.util.Set;
|
|
|
|
import java.util.stream.Collectors;
|
|
|
|
|
|
|
|
import org.springframework.beans.factory.annotation.Autowired;
|
2023-12-24 17:12:32 +00:00
|
|
|
import org.springframework.security.authentication.LockedException;
|
2023-08-13 01:14:30 +01:00
|
|
|
import org.springframework.security.core.GrantedAuthority;
|
|
|
|
import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
|
|
|
import org.springframework.security.core.userdetails.UserDetails;
|
|
|
|
import org.springframework.security.core.userdetails.UserDetailsService;
|
|
|
|
import org.springframework.security.core.userdetails.UsernameNotFoundException;
|
|
|
|
import org.springframework.stereotype.Service;
|
|
|
|
|
|
|
|
import stirling.software.SPDF.model.Authority;
|
|
|
|
import stirling.software.SPDF.model.User;
|
|
|
|
import stirling.software.SPDF.repository.UserRepository;
|
|
|
|
|
|
|
|
@Service
|
|
|
|
public class CustomUserDetailsService implements UserDetailsService {
|
|
|
|
|
2023-12-30 19:11:27 +00:00
|
|
|
@Autowired private UserRepository userRepository;
|
|
|
|
|
|
|
|
@Autowired private LoginAttemptService loginAttemptService;
|
2023-08-13 01:14:30 +01:00
|
|
|
|
|
|
|
@Override
|
|
|
|
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
|
2023-12-30 19:11:27 +00:00
|
|
|
User user =
|
|
|
|
userRepository
|
|
|
|
.findByUsername(username)
|
|
|
|
.orElseThrow(
|
|
|
|
() ->
|
|
|
|
new UsernameNotFoundException(
|
|
|
|
"No user found with username: " + username));
|
2023-08-13 01:14:30 +01:00
|
|
|
|
2023-12-24 17:12:32 +00:00
|
|
|
if (loginAttemptService.isBlocked(username)) {
|
2023-12-30 19:11:27 +00:00
|
|
|
throw new LockedException(
|
|
|
|
"Your account has been locked due to too many failed login attempts.");
|
2023-12-24 17:12:32 +00:00
|
|
|
}
|
2023-12-30 19:11:27 +00:00
|
|
|
|
2023-08-13 01:14:30 +01:00
|
|
|
return new org.springframework.security.core.userdetails.User(
|
2023-12-30 19:11:27 +00:00
|
|
|
user.getUsername(),
|
|
|
|
user.getPassword(),
|
|
|
|
user.isEnabled(),
|
|
|
|
true,
|
|
|
|
true,
|
|
|
|
true,
|
|
|
|
getAuthorities(user.getAuthorities()));
|
2023-08-13 01:14:30 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
private Collection<? extends GrantedAuthority> getAuthorities(Set<Authority> authorities) {
|
|
|
|
return authorities.stream()
|
2023-12-30 19:11:27 +00:00
|
|
|
.map(authority -> new SimpleGrantedAuthority(authority.getAuthority()))
|
|
|
|
.collect(Collectors.toList());
|
2023-08-13 01:14:30 +01:00
|
|
|
}
|
|
|
|
}
|