/** 
 * SecurityServiceImpl.java
 * @author 임새미 
 * @since 2016. 10. 6.
 *
 *  	 수정일                     수정자                                       수정내용
 *  -------------	--------	---------------------------
 *  2016. 10. 6. 	    임새미				       최초생성
 * 
 */
package kcg.imis.sec.service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.annotation.Resource;

import kcg.imis.sec.LoginUserVO;
import kcg.imis.sec.mapper.SecurityMapper;

import org.springframework.security.access.hierarchicalroles.RoleHierarchy;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import egovframework.rte.fdl.security.userdetails.EgovUserDetails;

/**
  * @FileName : SecurityServiceImpl.java
  * @Project : 국제해양프로젝트
  * @Date : 2018. 3. 29. 
  * @작성자 : Moon
  * @변경이력 : 
  * @프로그램 설명 :
 */
public class SecurityServiceImpl implements UserDetailsService {

	@Resource(name = "securityMapper")
	SecurityMapper securityMapper;
	
	private RoleHierarchy roleHierarchy;
	
	/**
     * Role Hierarchy값을 설정한다.
     * 
     * @param roleHierarchy
     */
    public void setRoleHierarchy(RoleHierarchy roleHierarchy) {
        this.roleHierarchy = roleHierarchy;
    }
	

    /**
     * 사용자 정보를 DB에서 가져와 UserDetails 객체에 담아 반환한다.
     * 
     * @param userId 사용자 아이디
     * @return UserDetails 객체
     */
	@Override
	public UserDetails loadUserByUsername(String userId) throws UsernameNotFoundException {
		
		LoginUserVO member = securityMapper.getUser(userId);
		List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
		
		if (member != null) {
			authorities.add(securityMapper.getAuthoritiesUser(userId));
		} else {
			throw new UsernameNotFoundException("접속자 정보를 찾을 수 없습니다.");
		}
        if (authorities.size() == 0) {
			throw new UsernameNotFoundException("User " + member.getUserid()+ " has no GrantedAuthority");
        }
        
		/* RoleHierarchyImpl 에서 저장한 Role Hierarchy 정보가 저장된다. */
        Collection<? extends GrantedAuthority> roleAuthorities = roleHierarchy.getReachableGrantedAuthorities(authorities);
        return new EgovUserDetails(member.getUserid(), member.getPasswd(), true, true, true, true, roleAuthorities, member);
	}

}
