package com.guwan.backend.security; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.guwan.backend.entity.User; import com.guwan.backend.mapper.UserMapper; 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 UserMapper userMapper; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { User user = userMapper.selectOne( new LambdaQueryWrapper<User>() .eq(User::getUsername, username) ); if (user == null) { throw new UsernameNotFoundException("用户不存在"); } if (user.getStatus() != 1) { throw new UsernameNotFoundException("账号已被禁用"); } List<SimpleGrantedAuthority> authorities = new ArrayList<>(); authorities.add(new SimpleGrantedAuthority("ROLE_USER")); return new CustomUserDetails( user.getId(), user.getUsername(), user.getPassword(), authorities, user.getStatus() == 1 ); } public UserDetails loadUserById(Long userId) throws UsernameNotFoundException { User user = userMapper.selectById(userId); if (user == null) { throw new UsernameNotFoundException("用户不存在"); } List<SimpleGrantedAuthority> authorities = new ArrayList<>(); authorities.add(new SimpleGrantedAuthority("ROLE_USER")); return new CustomUserDetails( user.getId(), user.getUsername(), user.getPassword(), authorities, user.getStatus() == 1 ); } }