JwtUserDetailsService.java
/**
* TFG 75.678 - TFG Desarrollo web 2020 e-Learning for Schools
* Copyright (C) 2020 Eduardo Rodriguez Carro
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.uoc.tfg.sel.security;
import java.util.Optional;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.context.annotation.Profile;
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 org.uoc.tfg.sel.repository.UserRepository;
import org.uoc.tfg.sel.repository.model.User;
import org.uoc.tfg.sel.security.model.UserDetailsExtended;
/**
* Servicio para la obtencion de los datos de usuario en el contexto de
* seguridad de Spring.
*
* @author Eduardo Rodriguez Carro
*/
@Profile("!test")
@Service
@Transactional
@CacheConfig(cacheNames = {"userLoginCache"})
public class JwtUserDetailsService implements UserDetailsService {
/** The user repository. */
@Autowired
private UserRepository userRepository;
/**
* Load user by username.
*
* @param username the username
* @return the user details
* @throws UsernameNotFoundException the username not found exception
*/
@Cacheable(key = "#username",unless = "#result != null")
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
Optional<User> user = userRepository.findByLoginAndActive(username,true);
if(user.isPresent()) {
return new UserDetailsExtended(user.get());
}
throw new UsernameNotFoundException(String.format("User not found with username: %s" , username));
}
}