@Entity
@Table(name="sp_user")
public class SpUser implements UserDetails {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long userId;
private String email;
private String password;
@OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@JoinColumn(name = "user_id", foreignKey = @ForeignKey(name="user_id"))
private Set<SpAuthority> authorities;
private boolean enabled;
@Override
public String getUsername() {
return email;
}
@Override
public boolean isAccountNonExpired() {
return enabled;
}
@Override
public boolean isAccountNonLocked() {
return enabled;
}
@Override
public boolean isCredentialsNonExpired() {
return enabled;
}
}
@Entity
@Table(name="sp_user_authority")
@IdClass(SpAuthority.class)
public class SpAuthority implements GrantedAuthority {
@Id
@Column(name="user_id")
private Long userId;
@Id
private String authority;
}
public interface SpUserRepository extends JpaRepository<SpUser, Long> {
Optional<SpUser> findUserByEmail(String email);
}
@Service
@Transactional
public class SpUserService implements UserDetailsService {
@Autowired
private SpUserRepository userRepository;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
return userRepository.findUserByEmail(username).orElseThrow(
()->new UsernameNotFoundException(username));
}
public Optional<SpUser> findUser(String email) {
return userRepository.findUserByEmail(email);
}
public SpUser save(SpUser user) {
return userRepository.save(user);
}
public void addAuthority(Long userId, String authority){
userRepository.findById(userId).ifPresent(user->{
SpAuthority newRole = new SpAuthority(user.getUserId(), authority);
if(user.getAuthorities() == null){
HashSet<SpAuthority> authorities = new HashSet<>();
authorities.add(newRole);
user.setAuthorities(authorities);
save(user);
}else if(!user.getAuthorities().contains(newRole)){
HashSet<SpAuthority> authorities = new HashSet<>();
authorities.addAll(user.getAuthorities());
authorities.add(newRole);
user.setAuthorities(authorities);
save(user);
}
});
}
public void removeAuthority(Long userId, String authority){
userRepository.findById(userId).ifPresent(user->{
if(user.getAuthorities()==null) return;
SpAuthority targetRole = new SpAuthority(user.getUserId(), authority);
if(user.getAuthorities().contains(targetRole)){
user.setAuthorities(
user.getAuthorities().stream().filter(auth->!auth.equals(targetRole))
.collect(Collectors.toSet())
);
save(user);
}
});
}
}
참고