
package nlib.user.web;

import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import nlib.util.UUID;

import javax.annotation.Resource;
import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import egovframework.com.ext.oauth.service.OAuthLogin;
import egovframework.com.ext.oauth.service.OAuthUniversalUser;
import egovframework.com.ext.oauth.service.OAuthVO;
import egovframework.rte.fdl.cryptography.EgovPasswordEncoder;
import nlib.cmm.NlibCommonController;
import nlib.cmm.crypto.AriaCrypto;
import nlib.cmm.service.NlibProperty;
import nlib.cmm.session.SessionConfig;
import nlib.info.service.InformService;
import nlib.mail.EmailSender;
import nlib.mail.service.EmailVO;
import nlib.user.service.LoginService;
import nlib.user.service.MemberService;
import nlib.user.service.NlibLoginVO;
import nlib.user.service.NlibSmsVO;
import nlib.user.service.UserInfoService;
import nlib.util.StringUtil;

import nlib.util.EmailUtil;


/**
 * <pre>
 * @Class Name : MemberController.java
 * 
 * @Description : 
 * 
 * 
 * @프로젝트명: 지방문화원 통합자료관리시스템 구축사업 (2021)
 *
 * </pre>
 *
 * @ ------------    --------    ---------------------------
 * @ 수정일                     수정자             수정내용
 * @ ------------    --------    ---------------------------
 * @ 2021. 7. 12.    JSYOO       최초 생성
 *
 * 
 * @author 이씨플라자 * DIGITALSHIP JSYOO
 * @since 2021. 7. 12.
 * @version 1.0
 *
 */

@Controller
public class MemberController extends NlibCommonController{
	
	//-------------------------------------------
		// SNS 연동 환경설정 정보 : context-oauth.xml 참고 
		//-------------------------------------------
		@Inject
		private OAuthVO naverAuthVO; /* 네이버 */
		
		@Inject
		private OAuthVO googleAuthVO; /* 구글 */

		@Inject
		private OAuthVO kakaoAuthVO; /* 카카오 */
		//-------------------------------------------
		
	@Resource(name="userInfoService")
	private UserInfoService userInfoService;
	
	@Resource(name="memberService")
	private MemberService memberService;
	
	@Resource(name="informService")
	private InformService informService;

	@Resource(name="loginService")
	private LoginService loginService;
	
	@Resource(name = "egovEnvPasswordEncoderService")
    EgovPasswordEncoder egovPasswordEncoder;
	
	@Resource(name = "ariaCrypto")
	private AriaCrypto ariaCrypto;
	
	@Resource(name = "emailUtil")
	private EmailUtil emailUtil;
	
	
	/* 이메일 메시지 및 템플릿 정보 */
	//템플릿 파일경로
	@Value("#{properties['mailing.sender.membership.signUpTemplate']}")
	private String signUpTemplate;
	
	@Value("#{properties['mailing.sender.membership.pwdTemplate']}")
	private String pwdTemplate;
	
	@Value("#{properties['mailing.sender.membership.certTemplate']}")
	private String certTemplate;
	
	//보내는 사람 이메일주소
	@Value("#{properties['mailing.sender.membership.email']}")
	private String senderAddr;
	
	//보내는 사람 이름
	@Value("#{properties['mailing.sender.membership.name']}")
	private String senderName;
	
	// SMS 보내는 사람 번호
	@Value("#{properties['sms.sender.phone.number']}")
	private String senderNumber;
	
	//hostName(이미지 접근)
	@Value("#{properties['host.name']}")
	private String hostName;
	
	//게스트 USERID
	@Value("#{properties['guest.userid']}")
	private String gUserId;
	
	//마이페이지 uri
	@Value("#{properties['mypage.uri']}")
	private String myPageUri;
	
	@Autowired
    private EmailSender emailSender;
	
	public ModelMap certificateMember(HttpServletRequest req)  {
		return null;
	}
	public ModelMap sendEmailForMemberJoining(HttpServletRequest req)  {
		return null;
	}
	public ModelMap changePassword(HttpServletRequest req)  {
		return null;
	}

	public ModelMap selectMemberInfo(HttpServletRequest req)  {
		return null;
	}

	public ModelMap updateMemberInfoForm(HttpServletRequest req)  {
		return null;
	}

	public ModelMap updateMemberInfo(HttpServletRequest req)  {
		return null;
	}

	public ModelMap leaveMember(HttpServletRequest req)  {
		return null;
	}
	
	/**
	 * 약관 동의화면
	 * @param req
	 * @param model
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value="/member/selectMemberJoiningInfo.do")
	public String selectMemberJoiningInfo(HttpServletRequest req,ModelMap model,HttpSession session) throws Exception  {
		//이용약관 및 개인정보제공동의
		HashMap<String, String> termRet = informService.selectTermsInfo(NlibProperty.getString("nlib.council.cd"));
		HashMap<String, String> privacyRet = informService.selectPrivacyInfo(NlibProperty.getString("nlib.council.cd"));
		
		String jsessionId = session.getId();
		OAuthUniversalUser oauthUser = SessionConfig.getNewMemberInfo(jsessionId);
		
		int count=0;
		
		//기 가입계정인지 확인
		count = memberService.selectSnsIdCount(oauthUser);
		if(count>0)
		{
			model.addAttribute("message", "이미 가입된 계정입니다. 로그인 후, 이용해 주시기 바랍니다.");
			model.addAttribute("loginBtnYn", "Y");
			return "nlib/login/loginMessage";
		}

    	model.addAttribute("termTitle", termRet.get("TITLE"));
    	model.addAttribute("termContent", termRet.get("CONTENT"));
    	
    	model.addAttribute("privacyTitle", privacyRet.get("TITLE"));
    	model.addAttribute("privacyContent", privacyRet.get("CONTENT"));
		return "/nlib/member/selectMemberJoiningInfo";
	}
	
	/**
	 * 회원가입 폼
	 * @exception Exception
	 */
	@RequestMapping(value="/member/insertMemberInfoForm.do")
	public String insertMemberInfoForm(HttpServletRequest request,NlibLoginVO vo,HttpSession session,ModelMap model ) throws Exception{
		String jsessionId = session.getId();
		OAuthUniversalUser oauthUser = SessionConfig.getNewMemberInfo(jsessionId);
		
		if(oauthUser == null)
		{
			model.addAttribute("msg","SNS인증이 정상적이지않습니다. 다시 회원가입을 진행해주세요.");
			model.addAttribute("url","${pageContext.request.contextPath}"+NlibProperty.getString("member.new.url"));
			return "nlib/cmm/alert";
		}
		// 등록된 ID가 있는 지 확인
		if(!(StringUtil.getString(oauthUser.getSnsUserId(),"")== ""))
			vo = memberService.selectAlreadySignUpId(oauthUser);
		
		/* 등록된 ID가 있을때 통합처리 */
		if(vo != null && !StringUtil.getString(vo.getMbInfoId(), "").equals(""))
		{
			oauthUser.setMbInfoId(vo.getMbInfoId());
			memberService.insertMemberSns(oauthUser);
			vo.setEmail(StringUtil.maskEmail(ariaCrypto.decode(vo.getEmail())));
			vo.setName(StringUtil.maskName(vo.getName()));
			oauthUser.setSnsUserId(StringUtil.maskEmail(oauthUser.getSnsUserId()));
			model.addAttribute("result",vo);
			model.addAttribute("oauthUser",oauthUser);
			//통합처리 url
			return "nlib/member/accountConsolidationForm";
		}
		model.addAttribute("loginVO",oauthUser);
		return "nlib/member/insertMemberInfoForm";
	}
	
	/**
	 * 동일한 핸드폰번호로 가입한 계정있을 시 통합팝업
	 * @exception Exception
	 */
	@RequestMapping(value="/member/selectAlreadySignUpMobilePopup.do")
	public String selectAlreadySignUpMobile(NlibLoginVO vo,ModelMap model,HttpSession session,HttpServletRequest request) throws Exception{
		List<NlibLoginVO> voList = new ArrayList<NlibLoginVO>();
		// 등록된 전화번호가 있는 지 확인 (리스트)
		voList = memberService.selectAlreadySignUpMobile(vo);
		
		vo.setMobileNo(ariaCrypto.decode(vo.getMobileNo()));
		
		//사용자ID 마스킹처리
		for(int i=0;voList.size()>i;i++)
		{
			voList.get(i).setEmail(StringUtil.maskEmail(ariaCrypto.decode(voList.get(i).getEmail())));
			voList.get(i).setName(StringUtil.maskName(voList.get(i).getName()));
		}
		
		model.addAttribute("cnt",voList.size());
		model.addAttribute("result",voList);
		model.addAttribute("vo",vo);
		return "nlib/member/alreadySignUpPopup";
	}
	
	/**
	 * 회원가입시 기존계정과 핸드폰번호가 일치할시 sns 계정통합
	 * @exception Exception
	 */
	@RequestMapping(value="/member/snsAccountLink.ajax" , method=RequestMethod.POST)
	public @ResponseBody String snsAccountLink(NlibLoginVO vo,HttpServletResponse response,Authentication authentication,ModelMap model,HttpServletRequest request,HttpSession session) throws Exception{
		String jsessionId = session.getId();
	    OAuthUniversalUser oauthUser = SessionConfig.getNewMemberInfo(jsessionId);
	    
	    if(oauthUser == null)
		{
			model.addAttribute("msg","SNS인증이 정상적이지않습니다. 다시 회원가입을 진행해주세요.");
			model.addAttribute("url","${pageContext.request.contextPath}"+NlibProperty.getString("member.new.url"));
			return "nlib/cmm/alert";
		}
	    
		NlibLoginVO loginVO = new NlibLoginVO();
		loginVO.setMbInfoId(vo.getMbInfoId());
		
		//사용자 정보를 가져온다.
		loginVO = userInfoService.selectMyInfo(loginVO);
	    
	    String msg="";
	    
	    String encodedText=null;
		encodedText = egovPasswordEncoder.encryptPassword(loginVO.getLoginUserId()+vo.getPassword());
		vo.setPassword(encodedText);
		
	    //암호화된 패스워드 비교
  		if(loginVO.getPassword().equals(vo.getPassword())) {
  		    oauthUser.setMbInfoId(vo.getMbInfoId());
			memberService.insertMemberSns(oauthUser);
			model.addAttribute("oauthUser",oauthUser);
			model.addAttribute("NlibLoginVO",vo);
  			msg="link";
  		}else {
  			msg="mismatch";
  		}
  		return msg;
	}
	
	/**
	 * 계정통합후 로그인
	 * @exception Exception
	 */
	@RequestMapping(value="/member/snsAccountLinkLogin.do")
	public String snsAccountLinkLogin(NlibLoginVO vo,ModelMap model,HttpSession session,HttpServletRequest request) throws Exception{
		String redirectUrl="";
		
		String url = request.getRequestURL().toString();
		String councilHomeUrl=url.replaceAll(request.getRequestURI(), "") + request.getContextPath();
		
		String jsessionId = session.getId();
	    OAuthUniversalUser oauthUser = SessionConfig.getNewMemberInfo(jsessionId);
	    
	    if(oauthUser == null)
		{
			model.addAttribute("msg","SNS인증이 정상적이지않습니다. 다시 회원가입을 진행해주세요.");
			model.addAttribute("url","${pageContext.request.contextPath}"+NlibProperty.getString("member.new.url"));
			return "nlib/cmm/alert";
		}
	    
		SessionConfig.setLoginInfo(jsessionId, oauthUser);
		session.setAttribute("councilReturnUrl","/member/accountConsolidationForm.do" );//로그인후 이동할페이지
		redirectUrl = councilHomeUrl + NlibProperty.getString("nculture.login.post.login.redirect.uri");
		
		return "redirect:" + redirectUrl;
	}
	
	/**
	 * 계정통합 결과폼
	 * @exception Exception
	 */
	@RequestMapping(value="/member/accountConsolidationForm.do")
	public String accountConsolidationForm(NlibLoginVO vo,ModelMap model,Authentication authentication,HttpSession session,HttpServletRequest request) throws Exception{
		//사용자 정보를 가져온다.
		NlibLoginVO loginVO = getNlibLoginVO(authentication);
		loginVO.setJoinCouncilCd(getCurCouncilCd(request));
		
		loginVO = loginService.selectLoginUserInfo(loginVO);
		loginVO.setEmail(StringUtil.maskEmail(loginVO.getEmail()));
		loginVO.setName(StringUtil.maskName(loginVO.getName()));
		
		String jsessionId = session.getId();
		OAuthUniversalUser oauthUser = SessionConfig.popNewMemberInfo(jsessionId);
		
		if(oauthUser == null)
		{
			model.addAttribute("msg","SNS인증이 정상적이지않습니다. 다시 회원가입을 진행해주세요.");
			model.addAttribute("url","${pageContext.request.contextPath}"+NlibProperty.getString("member.new.url"));
			return "nlib/cmm/alert";
		}
		
		model.addAttribute("result",loginVO);
		model.addAttribute("oauthUser",oauthUser);
		return "/nlib/member/accountConsolidationForm";
	}
	/**
	 * 회원가입
	 * @exception Exception
	 */
	@RequestMapping(value="/member/insertMemberInfo.do")
	public String insertMemberInfo(NlibLoginVO vo,ModelMap model,HttpSession session,HttpServletRequest request) throws Exception{
		
		String jsessionId = session.getId();
		OAuthUniversalUser oauthUser = SessionConfig.popNewMemberInfo(jsessionId);
		if(oauthUser != null && oauthUser.getNlibVO() != null)
		{
			//핸드폰인증시 sns제공 번호와 회원가입폼 번호 비교
			if(!(vo.getMobileNo().equals(oauthUser.getSnsMobileNo())))
			{
				if(!(vo.getMobileVrfctNo().equals(oauthUser.getNlibVO().getMobileVrfctNo()))
						||oauthUser.getNlibVO().getMobileVrfctDd() == null)  
				{
					model.addAttribute("msg","핸드폰인증이 정상적이지않습니다. 다시 회원가입을 진행해주세요.");
					model.addAttribute("url","${pageContext.request.contextPath}"+NlibProperty.getString("member.new.url"));
					return "nlib/cmm/alert";
				}
			}
			//이메일인증시 sns제공 이메일과 회원가입폼 이메일 비교
			if(!(vo.getEmail().equals(oauthUser.getSnsUserId())))
			{
				if(!(vo.getEmailVrfctNo().equals(oauthUser.getNlibVO().getEmailVrfctNo()))
						||oauthUser.getNlibVO().getEmailVrfctDd() == null)  
				{
					model.addAttribute("msg","이메일인증이 정상적이지않습니다. 다시 회원가입을 진행해주세요.");
					model.addAttribute("url","${pageContext.request.contextPath}"+NlibProperty.getString("member.new.url"));
					return "nlib/cmm/alert";
				}
			}
		}
		//문화원코드
		String councilNm = (String)session.getAttribute("councilNm");
		//클라이언트 IP주소
		vo.setIp(getRemoteIP(request));
		
		//회원정보 insert 
		memberService.insertMemberInfo(vo);
		
		//sns 테이블 insert
		oauthUser.setMbInfoId(vo.getMbInfoId());
		
		memberService.insertMemberSns(oauthUser);
		
    	// 결과가 정상이면, 안내 메일 발송 
    	// > 템플릿파일에서 내용 mailing.sender.membership.signUpTemplate
    	// > 발송처리 요청 
		vo.setEmail(ariaCrypto.decode(vo.getEmail()));
		
		SimpleDateFormat format = new SimpleDateFormat ("yyyy/MM/dd HH:mm:ss");
		Date date = new Date();
		String time = format.format(date);
		
		Map<String, Object> replaceContents = new HashMap<String, Object>();
		replaceContents.put("${name}", vo.getName());
		replaceContents.put("${email}", vo.getEmail());
		replaceContents.put("${councilNm}", councilNm);
		replaceContents.put("${hostName}", hostName);
		replaceContents.put("${time}", time);
		emailUtil.sendEmail(vo.getEmail(),senderName +" 회원가입을 축하드립니다.",replaceContents,signUpTemplate);
        
		model.addAttribute("result",vo);
		return "nlib/member/insertMemberInfoResult";
	}
	/**
	 * 이메일 인증번호 발송
	 * @exception Exception
	 */
	@RequestMapping(value="/member/emailCertNum.ajax" , method=RequestMethod.POST)
	public @ResponseBody Map<String,String> emailCertNum(HttpServletResponse response,Authentication authentication,HttpServletRequest request,HttpSession session) throws Exception{
		String email = request.getParameter("email");
		//회원가입페이지와 정보수정페이지의 프로세스 분기를위해 가져옴
		String pageName = request.getParameter("pageName");
		
		Map<String,String> map = new HashMap<String,String>();
		
		OAuthUniversalUser authUser= new OAuthUniversalUser();
		authUser.setSnsUserId(email);
		authUser.setSnsEmail(email);
		
		String mbInfoId="";
		NlibLoginVO chk = new NlibLoginVO();
		chk = memberService.selectAlreadySignUpId(authUser);
		
		String jsessionId = session.getId();
		
		//사용자 정보를 가져온다. 회원가입페이지라면 null
		NlibLoginVO loginVO = getNlibLoginVO(authentication);
		mbInfoId= loginVO.getMbInfoId();
		
		//중복된 아이디가 있을시(로그인시 본인의 mbInfoId 와 동일한경우는 제외)
		if(chk != null && !(chk.getMbInfoId().equals(mbInfoId)))
		{
			
			map.put("msg","이미 사용중인 이메일입니다.");
	    	map.put("emailCertYn","N");
			return map;
		}
		
		//인증번호 생성
		String CertNumber=memberService.numberGen(6,1);
		
		//내 정보 페이지
		if("myInfo".equals(pageName))
		{
			loginVO.setEmailTemp(email);
			loginVO.setEmailVrfctNo(CertNumber);
			replaceNlibLoginVO(request, loginVO);
		}else 
		{
			OAuthUniversalUser oauthUser = SessionConfig.getNewMemberInfo(jsessionId);
			
			NlibLoginVO vo=oauthUser.getNlibVO();
			//이미 생성된 VO가 없을때
			if(vo == null)
				vo= new NlibLoginVO();
			
			vo.setEmail(email);
			vo.setEmailVrfctNo(CertNumber);
			oauthUser.setNlibVO(vo);
			SessionConfig.setNewMemberInfo(jsessionId,oauthUser);
			
		}
	
		//이메일 발송
		// 결과가 정상이면, 안내 메일 발송 
    	// > 템플릿파일에서 내용 mailing.sender.membership.certTemplate
    	// > 발송처리 요청 
		Map<String, Object> replaceContents = new HashMap<String, Object>();
    	
    	SimpleDateFormat format = new SimpleDateFormat ("yyyy/MM/dd HH:mm:ss");
		Date date = new Date();
		String time = format.format(date);
		
		String councilNm = (String)session.getAttribute("councilNm");
		
		replaceContents.put("${certNumber}", CertNumber);
		replaceContents.put("${time}", time);
		replaceContents.put("${hostName}", hostName);
		replaceContents.put("${councilNm}", councilNm);
		replaceContents.put("${name}", StringUtil.getString(loginVO.getName(),""));
		
		String result = emailUtil.sendEmail(email,senderName +" 이메일 인증번호입니다.",replaceContents,certTemplate);
		
		if(result == "templateFail")
		{
			map.put("msg","이메일 발송에 실패하였습니다. \\n관리자에게 문의하여 주시기 바랍니다.");
	    	map.put("emailCertYn","N");
			return map;
		}
		
    	map.put("msg","이메일 인증번호가 발송됐습니다.");
    	map.put("emailCertYn","Y");
		return map;
	}
	
	/**
	 * 이메일 인증번호 확인
	 * @exception Exception
	 */
	@RequestMapping(value="/member/emailCertNumChk.ajax" , method=RequestMethod.POST)
	public @ResponseBody String emailCertNumChk(HttpServletResponse response,Authentication authentication,HttpServletRequest request,HttpSession session) throws Exception{
		String email = request.getParameter("email");
		String emailVrfctNo = request.getParameter("emailVrfctNo");
		//회원가입페이지와 정보수정페이지의 프로세스 분기를위해 가져옴
		String pageName = request.getParameter("pageName");
		
		SimpleDateFormat format = new SimpleDateFormat ( "yyyy년 MM월dd일 HH시mm분ss초");
		Date time = new Date();
		
		//내 정보 페이지
		if("myInfo".equals(pageName))
		{
			//사용자 정보를 가져온다. 회원가입페이지라면 null
			NlibLoginVO loginVO = getNlibLoginVO(authentication);
			
			//이메일과 인증번호 확인
			if(loginVO.getEmailTemp().equals(email) && loginVO.getEmailVrfctNo().equals(emailVrfctNo))
			{
				loginVO.setEmailVrfctDd(format.format(time));
				replaceNlibLoginVO(request, loginVO);
				return "true";
			}else {
				return "false";
			}
			
		}else 
		{
			//세션에 저장
			String jsessionId = session.getId();
			OAuthUniversalUser oauthUser = SessionConfig.getNewMemberInfo(jsessionId);
			
		    if(oauthUser == null)
			{
		    	return "false";
			}
			//이메일과 인증번호 확인
			if(oauthUser.getNlibVO().getEmail().equals(email) && oauthUser.getNlibVO().getEmailVrfctNo().equals(emailVrfctNo))
			{
				
				NlibLoginVO sessionNlibLoginVO = oauthUser.getNlibVO();
				sessionNlibLoginVO.setEmailVrfctDd(format.format(time));
				oauthUser.setNlibVO(sessionNlibLoginVO);
				SessionConfig.setNewMemberInfo(jsessionId,oauthUser);
				return "true";
			}else {
				return "false";
			}
		}
	}
	
	/**
	 * 핸드폰 인증번호 발송
	 * @exception Exception
	 */
	@RequestMapping(value="/member/mobileCertNum.ajax" , method=RequestMethod.POST)
	public @ResponseBody void phoneCertNum(HttpServletResponse response,Authentication authentication,HttpServletRequest request,HttpSession session) throws Exception{
		String mobileNo = request.getParameter("mobileNo");
		
		//회원가입페이지와 정보수정페이지의 프로세스 분기를위해 가져옴
		String pageName = request.getParameter("pageName");
		
		//인증번호 생성
		String CertNumber=memberService.numberGen(6,1);
		
		//세션에 저장
		String jsessionId = session.getId();
		
		//내 정보 페이지
		if("myInfo".equals(pageName))
		{
			NlibLoginVO loginVO = getNlibLoginVO(authentication);
			loginVO.setMobileTemp(mobileNo);
			loginVO.setMobileVrfctNo(CertNumber);
			replaceNlibLoginVO(request, loginVO);
		}
		else {
			OAuthUniversalUser oauthUser = SessionConfig.getNewMemberInfo(jsessionId);
			
			NlibLoginVO vo=oauthUser.getNlibVO();
			//이미 생성된 VO가 없을때
			if(vo == null)
				vo= new NlibLoginVO();
			
			vo.setMobileNo(mobileNo);
			vo.setMobileVrfctNo(CertNumber);
			oauthUser.setNlibVO(vo);
			SessionConfig.setNewMemberInfo(jsessionId,oauthUser);
		}
		
		NlibSmsVO smsVO=new NlibSmsVO();
		smsVO.setCmid(UUID.getNlibCommonID("",32));
		smsVO.setDestPhone(mobileNo);
		smsVO.setSendPhone(senderNumber);
		smsVO.setMsgBody("[한국문화원연합회] 본인확인 인증번호 [" + CertNumber + "]를 입력해주세요.");
		//문자발송 솔루션
		memberService.sendSms(smsVO);
		//------------
	}
	
	/**
	 * 핸드폰 인증번호 확인
	 * @exception Exception
	 */
	@RequestMapping(value="/member/mobileCertNumChk.ajax" , method=RequestMethod.POST)
	public @ResponseBody String mobileCertNumChk(HttpServletResponse response,Authentication authentication,HttpServletRequest request,HttpSession session) throws Exception{
		String mobileNo = request.getParameter("mobileNo");
		String mobileVrfctNo = request.getParameter("mobileVrfctNo");
		//회원가입페이지와 정보수정페이지의 프로세스 분기를위해 가져옴
		String pageName = request.getParameter("pageName");
		
		SimpleDateFormat format = new SimpleDateFormat ( "yyyy년 MM월dd일 HH시mm분ss초");
		
		Date time = new Date();
		
		//내 정보 페이지
		if("myInfo".equals(pageName))
		{
			//사용자 정보를 가져온다. 회원가입페이지라면 null
			NlibLoginVO loginVO = getNlibLoginVO(authentication);
			
			//핸드폰번호와 인증번호 확인
			if(loginVO.getMobileTemp().equals(mobileNo) && loginVO.getMobileVrfctNo().equals(mobileVrfctNo))
			{
				loginVO.setMobileVrfctDd(format.format(time));
				replaceNlibLoginVO(request, loginVO);
				return "true";
			}else {
				return "false";
			}
		}else {
			//세션에 저장
			String jsessionId = session.getId();
			OAuthUniversalUser oauthUser = SessionConfig.getNewMemberInfo(jsessionId);
			
			if(oauthUser == null)
			{
		    	return "false";
			}
			
			//핸드폰번호와 인증번호 확인
			if(oauthUser.getNlibVO().getMobileNo().equals(mobileNo) && oauthUser.getNlibVO().getMobileVrfctNo().equals(mobileVrfctNo))
			{
				NlibLoginVO sessionNlibLoginVO = oauthUser.getNlibVO();
				sessionNlibLoginVO.setMobileVrfctDd(format.format(time));
				oauthUser.setNlibVO(sessionNlibLoginVO);
				SessionConfig.setNewMemberInfo(jsessionId,oauthUser);
				return "true";
			}else {
				return "false";
			}
		}
	}
	
	/**
	 * 회원탈퇴 폼
	 * @exception Exception
	 */
	@RequestMapping(value="/member/deleteMembershipForm.do")
	public String deleteMembershipForm(HttpServletResponse response,Authentication authentication,HttpServletRequest request,ModelMap model) throws Exception{
		//사용자 정보를 가져온다.
		NlibLoginVO loginVO = getNlibLoginVO(authentication);
		if(loginVO == null) {
			model.addAttribute("msg","잘못된 접근입니다. \\n장시간 대기로 다시 로그인 하신 후, 이용해 주시기 바랍니다.");
			model.addAttribute("url","${pageContext.request.contextPath}"+"/");
			return "nlib/cmm/alert";
		}
		loginVO.setJoinCouncilCd(getCurCouncilCd(request));
		
		loginVO = loginService.selectLoginUserInfo(loginVO);
		//이메일,이름 마스킹
		loginVO.setEmail(StringUtil.maskEmail(loginVO.getEmail()));
		loginVO.setName(StringUtil.maskName(loginVO.getName()));
		model.addAttribute("loginVO",loginVO);
		model.addAttribute("myPageUri",myPageUri);
		return "nlib/member/deleteMembershipForm";
	}
	
	/**
	 * 회원탈퇴
	 * @exception Exception
	 */
	@RequestMapping(value="/member/deleteMembership.ajax")
	public @ResponseBody String deleteMembership(Authentication authentication,HttpServletResponse response,HttpServletRequest request,ModelMap model) throws Exception{
		//사용자 정보를 가져온다.
		NlibLoginVO loginVO = getNlibLoginVO(authentication);
		if(loginVO == null) {
			model.addAttribute("msg","잘못된 접근입니다. \\n장시간 대기로 다시 로그인 하신 후, 이용해 주시기 바랍니다.");
			model.addAttribute("url","${pageContext.request.contextPath}"+"/");
			return "nlib/cmm/alert";
		}
		
		loginVO.setJoinCouncilCd(getCurCouncilCd(request));
				
		loginVO = loginService.selectLoginUserInfo(loginVO);
		String password = egovPasswordEncoder.encryptPassword(loginVO.getLoginUserId()+request.getParameter("password").trim());
		
		String message="";
		
		if(loginVO != null && (loginVO.getPassword().equals(password)))
		{
			//회원탈퇴
			memberService.deleteMembership(loginVO);
			
			OAuthUniversalUser oAuthVO = new OAuthUniversalUser();
			oAuthVO.setMbInfoId(loginVO.getMbInfoId());
			
			//sns 연동해제
			userInfoService.deleteSnsLink(oAuthVO);
			
	        message="delete";
		}else {
			message="mismatch";
		}
		
		return message;
	}
	
    /**
	 * 비밀번호초기화 폼
	 * @exception Exception
	 */
	@RequestMapping(value="/member/initPasswordFormPopup.do")
	public String searchIdForm(NlibLoginVO vo,HttpServletResponse response,HttpServletRequest request,ModelMap model) throws Exception{
		model.addAttribute("loginVO", vo);
		return "nlib/member/initPasswordFormPopup";
	}
	
	/**
	 * 비밀번호 초기화
	 * @exception Exception
	 */
	@RequestMapping(value="/member/initPassword.ajax")
	public @ResponseBody String initPassword(NlibLoginVO vo,HttpSession session,HttpServletResponse response,HttpServletRequest request,ModelMap model) throws Exception{
		String email = vo.getEmail();
		vo.setEmail("");
		int count =0;
		//mbinfo를 이용해 조회
		NlibLoginVO loginVO = userInfoService.selectMyInfo(vo);
		
		//일치하는 이메일이 있는지 확인
		List<OAuthUniversalUser> snsLoginVO = userInfoService.selectSnsSignUpList(vo);
		if(email.equals(loginVO.getEmail()) || email.equals(loginVO.getLoginUserId()))
		{
			count +=1;
		}
		for(int i = 0; snsLoginVO.size() > i;i++)
		{
			if(email.equals(snsLoginVO.get(i).getSnsUserId()))
				count +=1;
		}
		
		if(count == 0)
		{
			return "fail";
		}
		
		String name="";
		
		//내 정보 수정시 비밀번호 찾기 , 회원가입시 비밀번호찾기 메일발송시(마스킹) 차별화
		if(vo != null && "alreadySignUpPopup".equals(vo.getPreviousPage()) )
		{
			name = vo.getNameTemp();
		}else {
			name = loginVO.getName();
		}
		
		String message = null;
		
		//비밀번호 초기화 변수 생성
		String initPwd=memberService.createInitPwd();
		//vo.decodePrivateInfo();
		
		if(loginVO!=null)
		{
	    	// 결과가 정상이면, 안내 메일 발송 
	    	// > 템플릿파일에서 내용 mailing.sender.membership.pwdtemplate
	    	// > 발송처리 요청 
			
			SimpleDateFormat format = new SimpleDateFormat ("yyyy/MM/dd HH:mm:ss");
			Date date = new Date();
			String time = format.format(date);
			
			String councilNm = (String)session.getAttribute("councilNm");
			
			Map<String, Object> replaceContents = new HashMap<String, Object>();
			loginVO.setPassword(egovPasswordEncoder.encryptPassword(loginVO.getLoginUserId()+initPwd));
			replaceContents.put("${initPwd}", initPwd);
			replaceContents.put("${time}", time);
			replaceContents.put("${hostName}", hostName);
			replaceContents.put("${councilNm}", councilNm);
			replaceContents.put("${name}", name);
			message = emailUtil.sendEmail(email, senderName +" 비밀번호 초기화 안내메일입니다.",replaceContents,pwdTemplate);
			if("success".equals(message)) 
			{
				memberService.changePassword(loginVO);
			}
		}else {
			message="fail";
		}
		
		return message;
	}
	
	/**
	 * 비밀번호 변경
	 * @exception Exception
	 */
	@RequestMapping(value="/member/changePassword.ajax")
	public @ResponseBody String changePassword(Authentication authentication,HttpServletResponse response,HttpServletRequest request,ModelMap model) throws Exception{
		//사용자 정보를 가져온다.
		NlibLoginVO loginVO = getNlibLoginVO(authentication);
		
		String message="";
		
		if(loginVO == null) {
			message="fail";
			return message;
		}
		
		loginVO.setJoinCouncilCd(getCurCouncilCd(request));
				
		loginVO = loginService.selectLoginUserInfo(loginVO);
		
		String password=egovPasswordEncoder.encryptPassword(loginVO.getLoginUserId()+request.getParameter("password"));
		String newPassword=egovPasswordEncoder.encryptPassword(loginVO.getLoginUserId()+request.getParameter("newPassword"));
		
		if(loginVO!=null && loginVO.getPassword().equals(password))
		{
			loginVO.setPassword(newPassword);
			loginVO.encodePrivateInfo();
			//암호화된 비밀번호로 수정
			memberService.changePassword(loginVO);
	        message="success";
		}else {
			message="fail";
		}
		
		return message;
	}
	//클라이언트 IP 가져오기
	public static String getRemoteIP(HttpServletRequest request){
        String ip = request.getHeader("X-FORWARDED-FOR"); 
        
        //proxy 환경일 경우
        if (ip == null || ip.length() == 0) {
            ip = request.getHeader("Proxy-Client-IP");
        }

        //웹로직 서버일 경우
        if (ip == null || ip.length() == 0) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }

        if (ip == null || ip.length() == 0) {
            ip = request.getRemoteAddr() ;
        }
        
        return ip;
   }
}