yl-backend/src/main/java/com/guwan/backend/security/UserDetailsServiceImpl.java

52 lines
1.7 KiB
Java
Raw Normal View History

2024-12-06 20:36:28 +08:00
package com.guwan.backend.security;
2024-12-07 19:46:23 +08:00
import com.guwan.backend.dto.user.UserDTO;
import com.guwan.backend.service.UserService;
2024-12-06 20:36:28 +08:00
import lombok.RequiredArgsConstructor;
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 java.util.ArrayList;
import java.util.List;
@Service
@RequiredArgsConstructor
public class UserDetailsServiceImpl implements UserDetailsService {
2024-12-07 19:46:23 +08:00
private final UserService userService;
2024-12-06 20:36:28 +08:00
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
2024-12-07 19:46:23 +08:00
UserDTO user = userService.findByUsername(username);
2024-12-06 20:36:28 +08:00
if (user == null) {
throw new UsernameNotFoundException("用户不存在");
}
2024-12-07 19:51:53 +08:00
return convertToUserDetailsWithoutPassword(user);
2024-12-06 20:36:28 +08:00
}
public UserDetails loadUserById(Long userId) throws UsernameNotFoundException {
2024-12-07 19:46:23 +08:00
UserDTO user = userService.getUserById(userId);
2024-12-06 20:36:28 +08:00
if (user == null) {
throw new UsernameNotFoundException("用户不存在");
}
2024-12-07 19:51:53 +08:00
return convertToUserDetailsWithoutPassword(user);
2024-12-07 19:46:23 +08:00
}
2024-12-06 20:36:28 +08:00
2024-12-07 19:51:53 +08:00
private UserDetails convertToUserDetailsWithoutPassword(UserDTO user) {
2024-12-06 20:36:28 +08:00
List<SimpleGrantedAuthority> authorities = new ArrayList<>();
authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
2024-12-07 19:46:23 +08:00
2024-12-06 20:36:28 +08:00
return new CustomUserDetails(
2024-12-07 19:46:23 +08:00
user.getId(),
user.getUsername(),
2024-12-07 19:51:53 +08:00
null,
2024-12-07 19:46:23 +08:00
authorities,
user.getStatus() == 1
2024-12-06 20:36:28 +08:00
);
}
}