All Downloads are FREE. Search and download functionalities are using the official Maven repository.

security.AbstractSpringUserDetailsService Maven / Gradle / Ivy

The newest version!
package 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 com.github.jhonyscamacho.finaluser.domain.RoleGroup;
import com.github.jhonyscamacho.finaluser.domain.User;
import com.github.jhonyscamacho.finaluser.service.UserService;

import 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 email) throws UsernameNotFoundException {

		//User user = getUserService().findUser(email);
		User user = getUserService().findUser(email);
		
		UserSpringFramework userWrapper = null;

		if (user != null) {
			if (user.isAvailable()) {
				userWrapper = new UserSpringFramework(user, this.getRoleGroups(user));
			}
		}

		return userWrapper;
	}

	@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 getRoleGroups(User user) {
		List authorities = new ArrayList<>();

		for (RoleGroup g : user.getRoleGroups()) {
			authorities.add(new SimpleGrantedAuthority(g.getName().toUpperCase()));
		}
		return authorities;
	}
}