sakthivikram/geo-location
0
1package com.georeport.security;2 3import com.georeport.entity.User;4import com.georeport.repository.UserRepository;5import org.springframework.beans.factory.annotation.Autowired;6import org.springframework.security.core.authority.SimpleGrantedAuthority;7import org.springframework.security.core.userdetails.UserDetails;8import org.springframework.security.core.userdetails.UserDetailsService;9import org.springframework.security.core.userdetails.UsernameNotFoundException;10import org.springframework.stereotype.Service;11import org.springframework.transaction.annotation.Transactional;12 13import java.util.stream.Collectors;14 15/**16 * Custom UserDetailsService implementation.17 * Loads user details from database for Spring Security authentication.18 */19@Service20public class CustomUserDetailsService implements UserDetailsService {21 22 @Autowired23 private UserRepository userRepository;24 25 @Override26 @Transactional(readOnly = true)27 public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {28 User user = userRepository.findByEmail(email)29 .orElseThrow(() -> new UsernameNotFoundException(30 "User not found with email: " + email));31 32 return new org.springframework.security.core.userdetails.User(33 user.getEmail(),34 user.getPassword(),35 user.getIsActive(),36 true,37 true,38 true,39 user.getRoles().stream()40 .map(role -> new SimpleGrantedAuthority(role.getName().name()))41 .collect(Collectors.toList()));42 }43 44 /**45 * Load user by ID46 */47 @Transactional(readOnly = true)48 public UserDetails loadUserById(Long id) {49 User user = userRepository.findById(id)50 .orElseThrow(() -> new UsernameNotFoundException("User not found with id: " + id));51 52 return new org.springframework.security.core.userdetails.User(53 user.getEmail(),54 user.getPassword(),55 user.getIsActive(),56 true,57 true,58 true,59 user.getRoles().stream()60 .map(role -> new SimpleGrantedAuthority(role.getName().name()))61 .collect(Collectors.toList()));62 }63}64 