DatabaseUserDetailsService.java
/*
* +====================================================================+
* | Copyright (C) 2015 Rochester Institute of Technology, |
* | 103 Lomb Memorial Drive, Rochester, NY - 14623 |
* | All Rights Reserved. |
* +====================================================================+
* FILENAME
* DatabaseUserDetailsService.java
*
* AUTHOR
* @author Khanh Ho (kchisd at rit.edu)
*
* =====================================================================
*/
package edu.rit.coopeval.security.dao;
import java.util.Set;
import java.util.stream.Collectors;
import edu.rit.coopeval.dao.UserRepository;
import edu.rit.coopeval.model.User;
import edu.rit.coopeval.model.UserRole;
import edu.rit.coopeval.security.SecurityUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.*;
import org.springframework.stereotype.Component;
@Component("dbUserDetailsService")
public class DatabaseUserDetailsService implements UserDetailsService {
@Autowired
private UserRepository userRepo;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userRepo.findFirstByUsername(username);
if (user == null) {
throw new UsernameNotFoundException("User " + username + " could not be found");
}
// Load roles into GrantedAuthority
if (user.getRoles() != null) {
Set<GrantedAuthority> authorities = user.getRoles().stream()
.map(UserRole::getRole)
.map(SimpleGrantedAuthority::new)
.collect(Collectors.toSet());
return new SecurityUser(user, authorities);
}
return new SecurityUser(user);
}
}