2024-01-03 17:59:04 +00:00
|
|
|
package stirling.software.SPDF.config.security;
|
|
|
|
|
|
|
|
import java.util.Collection;
|
|
|
|
import java.util.Set;
|
|
|
|
|
|
|
|
import org.springframework.security.authentication.LockedException;
|
|
|
|
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 {
|
|
|
|
|
2024-12-24 09:52:53 +00:00
|
|
|
private final UserRepository userRepository;
|
2024-01-03 17:59:04 +00:00
|
|
|
|
2024-12-24 09:52:53 +00:00
|
|
|
private final LoginAttemptService loginAttemptService;
|
|
|
|
|
|
|
|
public CustomUserDetailsService(
|
|
|
|
UserRepository userRepository, LoginAttemptService loginAttemptService) {
|
|
|
|
this.userRepository = userRepository;
|
|
|
|
this.loginAttemptService = loginAttemptService;
|
|
|
|
}
|
2024-01-03 17:59:04 +00:00
|
|
|
|
|
|
|
@Override
|
|
|
|
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
|
|
|
|
User user =
|
|
|
|
userRepository
|
|
|
|
.findByUsername(username)
|
|
|
|
.orElseThrow(
|
|
|
|
() ->
|
|
|
|
new UsernameNotFoundException(
|
|
|
|
"No user found with username: " + username));
|
|
|
|
if (loginAttemptService.isBlocked(username)) {
|
|
|
|
throw new LockedException(
|
|
|
|
"Your account has been locked due to too many failed login attempts.");
|
|
|
|
}
|
2024-05-18 23:47:05 +02:00
|
|
|
if (!user.hasPassword()) {
|
|
|
|
throw new IllegalArgumentException("Password must not be null");
|
2024-05-12 19:58:34 +02:00
|
|
|
}
|
2024-01-03 17:59:04 +00:00
|
|
|
return new org.springframework.security.core.userdetails.User(
|
|
|
|
user.getUsername(),
|
|
|
|
user.getPassword(),
|
|
|
|
user.isEnabled(),
|
|
|
|
true,
|
|
|
|
true,
|
|
|
|
true,
|
|
|
|
getAuthorities(user.getAuthorities()));
|
|
|
|
}
|
|
|
|
|
|
|
|
private Collection<? extends GrantedAuthority> getAuthorities(Set<Authority> authorities) {
|
|
|
|
return authorities.stream()
|
|
|
|
.map(authority -> new SimpleGrantedAuthority(authority.getAuthority()))
|
2025-03-27 12:42:45 +00:00
|
|
|
.toList();
|
2024-01-03 17:59:04 +00:00
|
|
|
}
|
|
|
|
}
|