52 lines
1.7 KiB
Java
52 lines
1.7 KiB
Java
package com.guwan.backend.security;
|
|
|
|
import com.guwan.backend.dto.user.UserDTO;
|
|
import com.guwan.backend.service.UserService;
|
|
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 {
|
|
|
|
private final UserService userService;
|
|
|
|
@Override
|
|
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
|
|
UserDTO user = userService.findByUsername(username);
|
|
if (user == null) {
|
|
throw new UsernameNotFoundException("用户不存在");
|
|
}
|
|
return convertToUserDetailsWithoutPassword(user);
|
|
}
|
|
|
|
public UserDetails loadUserById(Long userId) throws UsernameNotFoundException {
|
|
UserDTO user = userService.getUserById(userId);
|
|
if (user == null) {
|
|
throw new UsernameNotFoundException("用户不存在");
|
|
}
|
|
return convertToUserDetailsWithoutPassword(user);
|
|
}
|
|
|
|
|
|
|
|
private UserDetails convertToUserDetailsWithoutPassword(UserDTO user) {
|
|
List<SimpleGrantedAuthority> authorities = new ArrayList<>();
|
|
authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
|
|
|
|
return new CustomUserDetails(
|
|
user.getId(),
|
|
user.getUsername(),
|
|
null,
|
|
authorities,
|
|
user.getStatus() == 1
|
|
);
|
|
}
|
|
} |