package kcg.imis.sec;

import java.util.Collection;

import javax.annotation.Resource;

import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

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

/**
  * @FileName : AuthenticationProvider.java
  * @Project : 국제해양프로젝트
  * @Date : 2018. 3. 29. 
  * @작성자 : Moon
  * @변경이력 : 
  * @프로그램 설명 :
 */
public class AuthenticationProvider extends DaoAuthenticationProvider {
	
	/**
	 * 사용자 서비스.
	 */
	/*@Resource(name = "memberService")
	private MemberService memberSerivce;*/
	
 
	@Override
	public Authentication authenticate(final Authentication authentication) throws AuthenticationException {
		
		String username = authentication.getName();
		String password = (String) authentication.getCredentials();
		
		EgovUserDetails user = null;
		Collection<? extends GrantedAuthority> authorities = null;
		Authentication auth = null;
		
		try {
			user = (EgovUserDetails) retrieveUser(username, (UsernamePasswordAuthenticationToken) authentication);
			
			if (!password.equalsIgnoreCase(user.getPassword())) {
			/*	MemberVO memberVO = new MemberVO();
				memberVO.setUserid(user.getUsername());*/
 				throw new BadCredentialsException(
 						String.format("비밀번호가 일치하지 않습니다. ")
 				);
			} 
			
			authorities = user.getAuthorities();
			auth = new UsernamePasswordAuthenticationToken(user, password, authorities);
		} catch (UsernameNotFoundException e) {
			logger.info(e.toString());
			throw new UsernameNotFoundException(e.getMessage());
		} catch (BadCredentialsException e) {
			logger.info(e.toString());
			throw new BadCredentialsException(e.getMessage());
		} catch (Exception e) {
			logger.info(e.toString());
			throw new RuntimeException(e.getMessage());
		}
		
		return auth;
	}
}
