
br.com.jhonsapp.authentication.security.AbstractSpringUserDetailsService Maven / Gradle / Ivy
package br.com.jhonsapp.authentication.security;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import org.springframework.security.core.GrantedAuthority;
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 br.com.jhonsapp.finaluser.domain.RoleGroup;
import br.com.jhonsapp.finaluser.domain.User;
import br.com.jhonsapp.finaluser.service.UserService;
import br.com.jhonsapp.web.configuration.WebConfiguration;
/**
* This class is responsible for providing details of the users needed to log
* in. In the applicationContext.xml file there is a reference for this class
* responsible for being the user authentication service.
**/
public abstract class AbstractSpringUserDetailsService
implements UserDetailsService {
private WebConfiguration configuration = new WebConfiguration();
private Class userServiceImpl;
public AbstractSpringUserDetailsService(Class userServiceImpl) {
this.userServiceImpl = userServiceImpl;
}
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = null;
if(isUserRest(username))
user = getUserService().findUserByRestToken(username);
else
user = getUserService().findUser(username);
if (user != null) {
if (user.isAvailable()) {
if(isUserRest(username)){
return new UserRestSpringFramework(user, this.getRoleGroups(user));
}else{
return new UserWebSpringFramework(user, this.getRoleGroups(user));
}
}
}
return null;
}
private boolean isUserRest(String restToken){
return restToken.length() == 64;
}
@SuppressWarnings("unchecked")
private S getUserService() {
try {
InitialContext ic = new InitialContext();
return (S) ic.lookup(getLookupPath());
} catch (NamingException e) {
e.printStackTrace();
return null;
}
}
private String getLookupPath() {
return "java:global/"
+ configuration.getEarProjectName() + "/"
+ configuration.getEjbProjectName() + "/"
+ userServiceImpl.getSimpleName() + "!" + UserService.class.getName();
}
private Collection extends GrantedAuthority> getRoleGroups(User user) {
List authorities = new ArrayList<>();
for (RoleGroup g : user.getRoleGroups()) {
authorities.add(new SimpleGrantedAuthority(g.getName().toUpperCase()));
}
return authorities;
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy