content: package com.konsol.beatstream.security;
  
  import com.konsol.beatstream.domain.Authority;
  import com.konsol.beatstream.domain.User;
  import com.konsol.beatstream.repository.UserRepository;
  import java.util.*;
  import org.hibernate.validator.internal.constraintvalidators.hv.EmailValidator;
  import org.slf4j.Logger;
  import org.slf4j.LoggerFactory;
  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.Component;
  
  /**
   * Authenticate a user from the database.
   */
  @Component("userDetailsService")
  public class DomainUserDetailsService implements UserDetailsService {
  
      private static final Logger LOG = LoggerFactory.getLogger(DomainUserDetailsService.class);
  
      private final UserRepository userRepository;
  
      public DomainUserDetailsService(UserRepository userRepository) {
          this.userRepository = userRepository;
      }
  
      @Override
      public UserDetails loadUserByUsername(final String login) {
          LOG.debug("Authenticating {}", login);
  
          if (new EmailValidator().isValid(login, null)) {
              return userRepository
                  .findOneByEmailIgnoreCase(login)
                  .map(user -> createSpringSecurityUser(login, user))
                  .orElseThrow(() -> new UsernameNotFoundException("User with email " + login + " was not found in the database"));
          }
  
          String lowercaseLogin = login.toLowerCase(Locale.ENGLISH);
          return userRepository
              .findOneByLogin(lowercaseLogin)
              .map(user -> createSpringSecurityUser(lowercaseLogin, user))
              .orElseThrow(() -> new UsernameNotFoundException("User " + lowercaseLogin + " was not found in the database"));
      }
  
      private org.springframework.security.core.userdetails.User createSpringSecurityUser(String lowercaseLogin, User user) {
          if (!user.isActivated()) {
              throw new UserNotActivatedException("User " + lowercaseLogin + " was not activated");
          }
          List<SimpleGrantedAuthority> grantedAuthorities = user
              .getAuthorities()
              .stream()
              .map(Authority::getName)
              .map(SimpleGrantedAuthority::new)
              .toList();
          return new org.springframework.security.core.userdetails.User(user.getLogin(), user.getPassword(), grantedAuthorities);
      }
  }
  