700===Dev Project/기본 게시판

자동 로그인 처리

블로글러 2019. 1. 17. 13:59

순서

1 (JSP, JS, CSS) <> 2 (Controller, Service, Interceptor+AOP) <> 3 (DAO, DTO(Model/Map)) <> 4 (XML, DB)




1 (JSP, JS, CSS)


loginForm.jsp


1
2
3
4
5
6
7
8
<form id="register" name="register"
            action="/member/login" method="post" onsubmit="return check();">
//action="Controller RequestMapping value"     
 
<input id="autoLogin" name="autoLogin"
                           fw-filter="" fw-label="자동로그인" fw-msg="" value="T"
                           type="checkbox"><label for="autoLogin">자동로그인</label>
 
</form>
cs


2 (Controller, Service,  Interceptor+AOP


LoginController.java


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
package com.member.login;
 
import java.io.PrintWriter;
import java.security.Key;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
 
import javax.annotation.Resource;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
 
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.util.WebUtils;
 
import com.kh.iclass.common.map.CommandMap;
import com.kh.iclass.common.util.RSAKeySet;
import com.kh.iclass.common.util.SequenceUtils;
 
@Controller
public class LoginController {
 
    String authNum = "";
 
    @Resource(name = "loginService")
    private LoginService loginService;
 
    @RequestMapping(value = "/adminError")
    public ModelAndView admin() throws Exception 
    {
        ModelAndView mv = new ModelAndView();
        
        mv.setViewName("error/access");
        return mv;
    }  
    
    // 로그인 폼
    @RequestMapping(value = "/loginForm")
    public ModelAndView loginForm(HttpSession session,HttpServletRequest request) throws Exception {
        ModelAndView mv = new ModelAndView();
        RSAKeySet keySet = new RSAKeySet();
 
        String beforeUrl=request.getHeader("Referer");
        session.setAttribute("Referer",beforeUrl);
        //Referer==http://localhost:8080/3T/main
        
        System.out.println(beforeUrl);
        
        /* 세션에 개인키 저장 */
        session.setAttribute("RSA_private", keySet.getPrivateKey());
        
        /* Front Side로 공개키 전달 */
        mv.addObject("Modulus", keySet.getPublicKeyModulus());
        mv.addObject("Exponent", keySet.getPublicKeyExponent());
        
        mv.setViewName("member/loginForm");
        return mv;
    }   
    
   //로그인 됨
    @SuppressWarnings({ "unchecked""null" })
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public ModelAndView loginComplete(CommandMap commandMap, HttpServletRequest request, HttpServletResponse response) throws Exception {
        ModelAndView mv = new ModelAndView();
        RSAKeySet keySet = new RSAKeySet();//암호
        
        HttpSession session = request.getSession();
 
        // 멤버 정보 가져오고
        Map<String, Object> chk2 = loginService.loginGo2(commandMap.getMap(),(Key)session.getAttribute("RSA_private")); //암호화 비번
        Map<String, Object> chk = loginService.loginGo(commandMap.getMap());
 
        
        if (chk2 == null) {
            /* 세션에 개인키 저장 */
            session.setAttribute("RSA_private", keySet.getPrivateKey());
            
            /* Front Side로 공개키 전달 */
            mv.addObject("Modulus", keySet.getPublicKeyModulus());
            mv.addObject("Exponent", keySet.getPublicKeyExponent());
            
            mv.setViewName("member/loginForm");
            mv.addObject("message""아이디나 비밀번호를 확인해주세요.");
            return mv;
        }
        
        // 아이디 값이 있으면
        else {
            
                // 세션에 아이디를 넣어라
                session.setAttribute("MEMBER_ID", commandMap.get("MEMBER_ID"));
                
                mv.addObject("MEMBER", chk2); //암호화 비번
                
                 // 쿠키 사용한다는게 체크되어 있으면...
                if(commandMap.get("autoLogin"!= null)
                {
                    // 쿠키를 생성하고 현재 로그인되어 있을 때 생성되었던 세션을 쿠키에 저장한다.
                    Cookie autoLogin = new Cookie("autoLogin", session.getId());
                    // 쿠키를 찾을 경로를 컨텍스트 경로로 변경해 주고...
                    autoLogin.setPath("/");
                    int amount = 60 * 60 * 24 * 7;
                    autoLogin.setMaxAge(amount); // 단위는 (초)임으로 7일정도로 유효시간을 설정해 준다.
                    // 쿠키를 적용해 준다.
                    response.addCookie(autoLogin); 
                    //
                    String SESSIONKEY = session.getId();
                    // currentTimeMills()가 1/1000초 단위임으로 1000곱해서 더해야함 
                    Date sessionLimit = new Date(System.currentTimeMillis() + (1000*amount));
                    // 현재 세션 id와 유효시간을 사용자 테이블에 저장한다.
                    commandMap.put("MEMBER_ID", commandMap.get("MEMBER_ID"));
                    commandMap.put("SESSIONKEY", SESSIONKEY);
                    commandMap.put("SESSIONLIMIT", sessionLimit);
                    
                    loginService.keepLogin(commandMap.getMap());
                }
 
                }        
            
    
}
cs



LoginService.java


1
2
3
4
5
6
7
8
9
10
11
12
13
14
package com.member.login;
 
import java.util.Map;
 
public interface LoginService {    
    // 자동로그인 체크한 경우에 사용자 테이블에 세션과 유효시간을 저장하기 위한 메서드
    void keepLogin(Map<String, Object> map) throws Exception; 
    
    // 이전에 로그인한 적이 있는지, 즉 유효시간이 넘지 않은 세션을 가지고 있는지 체크한다.
    public Map<String, Object> checkUserWithSessionKey(String SESSIONKEY);
    Map<String, Object> loginGo2(Map<String, Object> map, Key attribute) throws Exception;
    
}
 
cs



LoginServiceImpl.java


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package com.member.login;
 
import java.util.Map;
 
import javax.annotation.Resource;
 
import org.springframework.stereotype.Service;
 
import com..common.map.CommandMap;
 
@Service("loginService")
public class LoginServiceImpl implements LoginService{
 
    @Resource(name="loginDAO")
    private LoginDAO loginDAO;
 
    // 자동로그인 체크한 경우에 사용자 테이블에 세션과 유효시간을 저장하기 위한 메서드
    @Override
    public void keepLogin(Map<String, Object> map) throws Exception
    {
        loginDAO.keepLogin(map);
    }
    
    // 이전에 로그인한 적이 있는지, 즉 유효시간이 넘지 않은 세션을 가지고 있는지 체크한다.
    @Override
    public Map<String, Object> checkUserWithSessionKey(String SESSIONKEY) {
        return loginDAO.checkUserWithSessionKey(SESSIONKEY);
 
    }
        
}
 
cs


AutoLoginInterceptor.java


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package com.member.login;
 
import java.util.Map;
 
import javax.inject.Inject;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
 
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.springframework.web.util.WebUtils;
 
public class AutoLoginInterceptor extends HandlerInterceptorAdapter{
 
     @Inject
     LoginService loginService;
 
//메소드 preHandle()
//파라미터: HttpServletRequest request, HttpServletResponse response, Object handler
//리턴: boolean 
 
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception 
    {           
        // session 객체를 가져옴
        HttpSession session = request.getSession();
      
        // login처리를 담당하는 사용자 정보를 담고 있는 객체를 가져옴
        Object obj = session.getAttribute("MEMBER_ID");
 
        // 로그인된 세션이 없는 경우...
        if ( obj == null )
        { 
            // 우리가 만들어 논 쿠키를 꺼내온다.
            Cookie autoLogin = WebUtils.getCookie(request, "autoLogin");
            
 
            // 쿠키가 존재하는 경우(이전에 로그인때 생성된 쿠키가 존재한다는 것)
            if ( autoLogin != null )
            { 
                // autoLogin의 값을 꺼내오고 -> 즉, 저장해논 세션Id를 꺼내오고
                String SESSIONKEY = autoLogin.getValue();
                
                Map<String, Object> chk = loginService.checkUserWithSessionKey(SESSIONKEY);
                
                if(chk != null)
                {
                     session.setAttribute("MEMBER_ID", chk.get("MEMBER_ID").toString());
                     
                     return true;
                }
                
              }
            
            // 이제 아래는 로그인도 안되있고 쿠키도 존재하지 않는 경우니까 다시 로그인 폼으로 돌려보내면 된다.
            // 로그인이 안되어 있는 상태임으로 로그인 폼으로 다시 돌려보냄(redirect)
            
            return true
      
        }
 
        return true;
 
    }
  
    //preHandel -> controller 이벤트 호출전
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception 
    {
        super.postHandle(request, response, handler, modelAndView);
    }
 
}
 
cs



3 (DAO, DTO(Model/Map))


AbstractDao.java


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package com.kh.iclass.common.dao;
 
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
 
public class AbstractDAO {
    protected Log log = LogFactory.getLog(AbstractDAO.class);
 
    @Autowired
    private SqlSessionTemplate sqlSession;
 
    protected void printQueryId(String queryId) {
        if (log.isDebugEnabled()) {
            log.debug("\t QueryId  \t:  " + queryId);
        }
    }
 
    public Object update(String queryId, Object params) {
        printQueryId(queryId);
        return sqlSession.update(queryId, params);
    }
 
    public Object selectOne(String queryId, Object params) {
        printQueryId(queryId);
        return sqlSession.selectOne(queryId, params);
    }    
 
}
 
cs


LoginDao.java


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package com.member.login;
 
import java.util.Map;
 
import org.springframework.stereotype.Repository;
 
import com.kh.iclass.common.dao.AbstractDAO;;
 
@Repository("loginDAO")
public class LoginDAO extends AbstractDAO {
 
    // 자동로그인 체크한 경우에 사용자 테이블에 세션과 유효시간을 저장
    public void keepLogin(Map<String, Object> map) throws Exception {
 
        update("member.keepLogin", map);
    }
    // 이전에 로그인한 적이 있는지, 즉 유효시간이 넘지 않은 세션을 가지고 있는지 체크한다.
    public Map<String, Object> checkUserWithSessionKey(String SESSIONKEY) {
        return (Map<String, Object>) selectOne("member.checkUserWithSessionKey", SESSIONKEY);
    }
 
    
}
 
cs



 4 (XML, DB)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<!-- 자동로그인 기간설정 -->
    <update id="keepLogin">
        UPDATE 
            MEMBER 
        SET
            SESSIONKEY = #{SESSIONKEY}, 
            SESSIONLIMIT = #{SESSIONLIMIT} 
        WHERE 
            MEMBER_ID = #{MEMBER_ID}
    </update>
    
    <!-- 자동로그인 세션id로저장 -->
    <select id="checkUserWithSessionKey" parameterType="String" resultType="hashmap">
        SELECT
            MEMBER_NO,
            MEMBER_ID, 
            PASSWD, 
            NAME, 
            BIRTH, 
            ZIPCODE, 
            ADDR1, 
            ADDR2, 
            PHONE, 
            EMAIL,
            SESSIONKEY
        FROM 
            MEMBER 
        WHERE 
            SESSIONKEY = #{SESSIONKEY} AND 
            SESSIONLIMIT > SYSDATE
    </select>
cs


728x90

'700===Dev Project > 기본 게시판' 카테고리의 다른 글

매우 기초적인 회원가입시 공백 검증(Validation)  (0) 2019.01.17
회원가입  (0) 2019.01.14